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>
相关推荐
全栈小52 天前
【数据库】浙人医携手金仓数据库,打造全国首个多院区异构多活容灾架构
数据库·1024程序员节·金仓
CoderYanger4 天前
贪心算法:7.最长连续递增序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger4 天前
贪心算法:6.递增的三元子序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger4 天前
贪心算法:1.柠檬水找零
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger4 天前
贪心算法:4.摆动序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger4 天前
贪心算法:2.将数组和减半的最少操作次数
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger4 天前
贪心算法:8.买卖股票的最佳时机
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger4 天前
贪心算法:3.最大数
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger4 天前
贪心算法:5.最长递增子序列
java·算法·leetcode·贪心算法·1024程序员节
liguojun20255 天前
智慧破局:重构体育场馆的运营与体验新生态
java·大数据·人工智能·物联网·重构·1024程序员节