Vue3 + Element Plus 封装文本超出长度显示省略号,鼠标移上悬浮展示全部内容的组件

一、背景介绍:

基于Vue3 + Element Plus的项目,多处出现展示超长文本,为了页面美观,笔者决定封装成Text组件,实现"文本超出长度显示省略号,鼠标移上悬浮展示全部内容"的功能。

二、封装的Text组件

javascript 复制代码
<template>
  <el-tooltip
    effect="dark"
    :content="text"
    :disabled="isShowTooltip"
  >
    <div
      class="outer"
      :style="style"
      @mouseover="onMouseOver()"
    >
      <span ref="innerText">
        {{ content }}
      </span>
    </div>
  </el-tooltip>
</template>

<script setup lang="ts">
  import { ref, watchEffect } from 'vue'
  const props = defineProps({
    text: {
      type: String,
      default: ''
    },
    style: {
      type: Object,
      default: {}
    }
  })

  const { text, style } = props
  const innerText = ref<any>(null)
  const isShowTooltip = ref<boolean>(false)
    const onMouseOver = () => {
    const parentWidth = innerText.value.parentNode.offsetWidth // 获取元素父级可视宽度
    const contentWidth = innerText.value.offsetWidth // 获取元素可视宽度
    isShowTooltip.value = contentWidth <= parentWidth
  }

  const content = ref<string>('')
  watchEffect(() => {
    content.value = props.text
  })
</script>

<style lang="scss" scoped>
.outer {
  width: 100%;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}
</style>

三、Text组件的使用

javascript 复制代码
<template>
  <div>
    <Text
      :text="content"
      :style="{
        marginLeft: '6px',
        fontSize: '14px'
      }"
    ></Text>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import Text from '@/components/Text.vue' // Text.vue在项目中的路径
const content = ref<string>('你好')
</script>

<style>
</style>
相关推荐
mjhcsp2 小时前
C++ 动态规划(Dynamic Programming)详解:从理论到实战
c++·动态规划·1024程序员节
金融小师妹1 天前
基于机器学习框架的上周行情复盘:非农数据与美联储政策信号的AI驱动解析
大数据·人工智能·深度学习·1024程序员节
渣渣盟1 天前
Flink分布式文件Sink实战解析
分布式·flink·scala·1024程序员节
CoderYanger1 天前
优选算法-栈:69.验证栈序列
java·开发语言·算法·leetcode·职场和发展·1024程序员节
金融小师妹3 天前
基于机器学习与深度强化学习:非农数据触发AI多因子模型预警!12月降息预期骤降的货币政策预测
大数据·人工智能·深度学习·1024程序员节
紫麦熊4 天前
react+ts+vite+tailwind+shadcn
1024程序员节
日日行不惧千万里4 天前
MediaMTX详解
1024程序员节
金融小师妹4 天前
基于LSTM-GARCH模型:三轮黄金周期特征提取与多因子定价机制解构
人工智能·深度学习·1024程序员节
自信150413057594 天前
初学者小白复盘23之——联合与枚举
c语言·1024程序员节
CoderYanger6 天前
B.双指针——3194. 最小元素和最大元素的最小平均值
java·开发语言·数据结构·算法·leetcode·职场和发展·1024程序员节