欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > Vue3 + Element Plus 封装文本超出长度显示省略号,鼠标移上悬浮展示全部内容的组件

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

2025/2/24 13:18:52 来源:https://blog.csdn.net/ling08140814/article/details/143212773  浏览:    关键词:Vue3 + Element Plus 封装文本超出长度显示省略号,鼠标移上悬浮展示全部内容的组件

一、背景介绍:

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

二、封装的Text组件

<template><el-tooltipeffect="dark":content="text":disabled="isShowTooltip"><divclass="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 } = propsconst 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组件的使用

<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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词