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>
相关推荐
CoderYanger8 小时前
A.每日一题——2435. 矩阵中和能被 K 整除的路径
开发语言·线性代数·算法·leetcode·矩阵·深度优先·1024程序员节
CoderYanger20 小时前
递归、搜索与回溯-穷举vs暴搜vs深搜vs回溯vs剪枝:12.全排列
java·算法·leetcode·机器学习·深度优先·剪枝·1024程序员节
QQ207952355921 小时前
基于机器学习的农产品价格数据分析与预测的可视化系统毕业设计项目源码
1024程序员节
金融小师妹1 天前
基于LSTM-GARCH混合模型:降息预期驱动金价攀升,白银刷新历史峰值的蒙特卡洛模拟验证
大数据·人工智能·深度学习·1024程序员节
普通网友1 天前
‌Flutter vs Kotlin:移动开发的未来趋势与选择
1024程序员节
我来整一篇1 天前
[油猴脚本] 微软必应奖励每日任务脚本
1024程序员节
金融小师妹1 天前
AI视角下黄金避风港属性的量化验证:基于2000-2025年历史数据的时序分析
大数据·人工智能·深度学习·1024程序员节
君以思为故1 天前
认识linux -- 进程控制
linux·运维·1024程序员节
CoderYanger1 天前
递归、搜索与回溯-记忆化搜索:40.矩阵中的最长递增路径
java·线性代数·算法·leetcode·矩阵·1024程序员节
xcLeigh1 天前
KingbaseES数据库:首个多院区异构多活容灾架构,浙人医创新开新篇
国产数据库·1024程序员节·kingbasees·金仓数据库