一、效果
为什么不直接使用element-ui提供的el-tooltip?
- el-tooltip组件一旦使用,不管文本有没有显示完整,鼠标移入都会有浮层提示
- el-table的show-overflow-tooltip属性可以做到第一点,但是不支持行数配置
二、Tooltip组件
<template>
<el-tooltip v-bind="$attrs" :disabled="disabled" popper-class="tootltip-popper">
<div
class="title-line-ellipsis"
:style="`-webkit-line-clamp: ${row}`"
@mouseenter="handleMouseenter($event)"
>
{{ $attrs.content }}
</div>
</el-tooltip>
</template>
<script>
export default {
name: 'Tooltip',
props: { row: { type: [String, Number], default: 1 } },
data() {
return { disabled: true }
},
methods: {
// 鼠标移入时,如果实际内容高度(clientHeight)等于滚动高度(scrollHeight),则禁用 tooltip
handleMouseenter(e) {
const { clientHeight, scrollHeight } = e.target
this.disabled = clientHeight === scrollHeight
}
}
}
</script>
<style scoped>
.title-line-ellipsis {
flex: 1;
text-overflow: ellipsis;
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
word-wrap: break-word; /* 解决英文的情况下不出现省略号 */
text-align: justify; /* 优化 word-wrap: break-word; 带来的留白 */
}
</style>
<style>
.tootltip-popper {
max-width: 70vw;
}
</style>
三、使用
<span class="wrapper">
<Tooltip :content="val" placement="top" row="3" />
</span>
<div class="wrapper">
<Tooltip :content="val1" placement="top" row="3" />
</div>
<span class="wrapper">
<Tooltip :content="val2" placement="top" row="3" />
</span>
data
data() {
return {
val: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
val1: '备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注备注',
val2: '??????????????????????????????????????????????????????????????'
}
}
.wrapper {
/deep/.el-tooltip {
border: 5px solid red;
padding: 2px;
}
}
如果你觉得这篇文章对你有用,可以看看作者封装的库xtt-utils,里面封装了非常实用的js方法。如果你也是vue开发者,那更好了,除了常用的api,还有大量的基于element-ui组件库二次封装的使用方法和自定义指令等,帮你提升开发效率。不定期更新,欢迎交流~