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>
相关推荐
lzb_kkk18 天前
【MFC】编辑框、下拉框、列表控件
c语言·开发语言·c++·mfc·1024程序员节
lzb_kkk20 天前
【MFC】树控件的使用详解
开发语言·c++·windows·mfc·1024程序员节
SizeTheMoment1 个月前
List介绍
1024程序员节
开利网络2 个月前
产业互联网+三融战略:重构企业增长密码
大数据·运维·服务器·人工智能·重构·1024程序员节
wei_shuo2 个月前
从数据中台到数据飞轮:实现数据驱动的升级之路
1024程序员节·数据飞轮
玖剹2 个月前
矩阵区域和 --- 前缀和
数据结构·c++·算法·leetcode·矩阵·动态规划·1024程序员节
jamison_13 个月前
文心一言与 DeepSeek 的竞争分析:技术先发优势为何未能转化为市场主导地位?
人工智能·ai·chatgpt·gpt-3·1024程序员节
NaZiMeKiY3 个月前
HTML5前端第六章节
前端·html·html5·1024程序员节
jamison_13 个月前
颠覆未来:解锁ChatGPT衍生应用的无限可能(具体应用、功能、付费模式与使用情况)
ai·chatgpt·1024程序员节
NaZiMeKiY4 个月前
HTML5前端第七章节
1024程序员节