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>
相关推荐
Wang's Blog1 小时前
Linux小课堂: 基于 SSH 的安全文件传输与增量同步机制深度解析之从 wget 到 rsync 的全流程实战
linux·ssh·1024程序员节
mit6.8241 小时前
[OP-Agent] `opa run` | 交互模式(REPL) | 服务模式(HTTP API) | runtime包
go·1024程序员节
Apipost的同学们1 小时前
API测试工具进化:从Postman到Apipost的全局参数管理革命
postman·api测试·1024程序员节·apipost·参数管理·全局参数管理
More more1 小时前
纯css实现任务头像叠加
1024程序员节
on_pluto_1 小时前
【基础复习1】ROC 与 AUC:逻辑回归二分类例子
人工智能·机器学习·职场和发展·学习方法·1024程序员节
tianyuanwo2 小时前
计算机网络设计:从基础到原则的体系化指南
计算机网络·路由器·交换机·1024程序员节
β添砖java3 小时前
vivo响应式官网
前端·css·html·1024程序员节
er_rui3 小时前
U167571 信使
1024程序员节
成震19713 小时前
esp-idf 最简操作
1024程序员节
2301_803554523 小时前
详细解释 std::thread t1(&ThreadPrinter::print, &printer, 1);
1024程序员节