需求
当文本超出的时候需要显示点点点,然后鼠标悬浮其上要能查看所有的文本内容。就直接封装一个通用的组件。
依赖项
- element-plus
- vue3
组件存放目录
新建vue文件/components/overflow-tooltip/OverflowTooltip.vue
组件代码
<template>
<el-tooltip v-if="isShowTip" effect="light" :content="text">
<div class="overflow-tooltip-text" :style="{ width: width, display: display }">{{ text }}</div>
</el-tooltip>
<div v-else :id="id" class="overflow-tooltip-text" :style="{ width: width, display: display }">{{ text }}</div>
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
const props = defineProps({
text: {
type: String,
required: true
},
width: {
type: String,
required: true
},
id: {
type: String,
required: true,
default: () => 'ot' + Math.floor(Math.random() * 100000000)
},
display: {
type: String,
required: true,
default: 'inline-block'
}
})
const isShowTip = ref(false)
watch(
() => props.text,
async function () {
await nextTick()
const idEle = document.getElementById(props.id)
if (!idEle) return
let style = window.getComputedStyle(idEle, null)
let paddingL = parseFloat(style.getPropertyValue('padding-left')) //获取左侧内边距
let paddingR = parseFloat(style.getPropertyValue('padding-right')) //获取右侧内边距
//超出则可鼠标悬浮查看全部内容
isShowTip.value = idEle.scrollWidth > idEle.clientWidth - paddingL - paddingR
},
{ immediate: true }
)
</script>
<style scoped>
.overflow-tooltip-text {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
</style>
组件使用
<template>
<!-- 会显示点点点 -->
<OverflowTooltip width="50px" text="999999999999999999999999" />
<br />
<!-- 不会显示点点点 -->
<OverflowTooltip width="50px" text="123" />
</template>
<script setup lang="ts">
import OverflowTooltip from '@/components/overflow-tooltip/OverflowTooltip.vue'
</script>
标签:vue,悬浮,text,idEle,组件,overflow,true
From: https://www.cnblogs.com/cluyun/p/16919276.html