方法一:
需求:超出10字符时,超出部分用…代替,悬停展示全部,否则正常显示
代码如下:
<template>
<div>
<el-tooltip
placement="top"
:content="test"
v-if="test.length > 10">
<span>{{test.slice(0, 10) + '...'}}</span>
</el-tooltip>
<span v-else>{{test}}</span>
</div>
</template>
字符数为10时:
<script>
export default {
data() {
return {
test: '生活不易,还得继续啊'
}
}
}
</script>
显示如下:
字符数超过10时:
<script>
export default {
data() {
return {
test: '生活不易,还得继续,你说是吗?'
}
}
}
</script>
显示如下:
方法二:
根据宽度过长自动显示省略,鼠标悬浮则显示tooltip
写一个名字为tooltip的组件:
tooltip.vue
<template>
<!-- :disabled="disabledTip" -->
<el-tooltip
ref="tlp"
:content="text"
effect="dark"
:disabled="!tooltipFlag"
:placement="placement"
:visible-arrow="true"
class="tooltip"
>
<span :class="className" @mouseenter="visibilityChange($event)">{{ text }}</span>
</el-tooltip>
</template>
<script>
export default {
name: 'Tooltip',
props: {
text: { type: String, default: '' }, // 字符内容
placement: { type: String, default: 'top-start' },
className: { type: String, default: 'text' } // class
},
data() {
return {
disabledTip: false,
tooltipFlag: false
}
},
methods: {
// tooltip的可控
visibilityChange(event) {
const ev = event.target
const ev_height = ev.offsetWidth // 文本的实际高度
const content_height = this.$refs.tlp.$el.parentNode.clientWidth // 文本容器高度
if (content_height < ev_height) {
// 实际内容高度 > 文本高度 =》内容溢出
this.tooltipFlag = true // NameIsIncludeWord ? true : !!false
} else {
// 否则为不溢出
this.tooltipFlag = false
}
console.log('this.tooltipFlag!!!', this.tooltipFlag, content_height, ev_height)
}
}
}
</script>
<style scoped lang="scss">
</style>
对tooltip组件的使用:
<span class="tooltip-wrap">
<tooltip
:text="pInfo.postDeptCode"
:placement="test1"
/>
</span>
<script>
import Tooltip from './Tooltip'
export default {
components: {
Tooltip
},
.tooltip-wrap {
width: 80px; // 必须要有高度设置,因为tooltip的显示条件是通过高度来判断的
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
vertical-align: top;
}
效果图:
参考文章:
https://blog.csdn.net/weixin_44717761/article/details/106022888
https://blog.csdn.net/weixin_41628411/article/details/107057506