-
新建组件 myTooltip.vue(可直接复制使用)
<template>
<div class="tooltip-container">
<el-tooltip class="my-tooltip" :disabled="showTooltip" :content="text">
<p ref="tooltipBox" class="text-box">
<span ref="tooltipItem">{{ text }}</span>
</p>
</el-tooltip>
</div>
</template><script>
export default {
props: {
text: {
type: String,
default: () => ''
}
},
data() {
return {
showTooltip: true
}
},
watch: {
text: {
handler() {
this.$nextTick(() => this.checkWidth())
},
immediate: true
}
},
methods: {
checkWidth() {
const boxWidth = this.$refs['tooltipBox'].offsetWidth
const itemWidth = this.$refs['tooltipItem'].offsetWidth
console.log(boxWidth, itemWidth)
this.showTooltip = boxWidth > itemWidth
}
}
}
</script>
<style scoped lang="scss">
.tooltip-container {
width: 100%;
.text-box {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin: 0;
}
}
</style>
2. 使用组件
// 引入组件
import myTooltip from '../../components/myTooltip'components: { myTooltip },
// 使用组件, 将需要展示的文字传递过去,
<myTooltip :text="文字啊........." />
// 注意: 组件内的宽度设置为100%, 是继承父元素的宽度, 所以需要设定父元素的宽度