原理就是在鼠標浮動到el-tootip
包裹的元素時判斷該元素的scrollWidth
(元素內(nèi)容的實際寬度)有沒有超過clientWidth
(元素的可是寬度)超出時顯示省略號并設置disabled
屬性為false
否則為true
代碼如下:
<el-tooltip placement="top" :content="title" :disabled="isShowTooltip">
<span @mouseenter="visibilityChange($event)">{{title}}</span>
</el-tooltip>
data () {
return {
isShowTooltip: false
}
},
methods: {
visibilityChange (event) {
const ev = event.target
const evWeight = ev.scrollWidth
const contentWeight = ev.clientWidth
if (evWeight > contentWeight) {
// 實際寬度 > 可視寬度 文字溢出
this.isShowTooltip = false
} else {
// 否則為不溢出
this.isShowTooltip = true
}
}
}
但是由于項目中用到el-tootip
的地方太多了所以為了不想寫太多次也可以把這部分注冊成全局指令:
Vue.directive('is-tip', {
bind (el, bind, vnode, oldnode) {
el.addEventListener('mouseenter', () => {
if (vnode.child.$el.scrollWidth > vnode.child.$el.clientWidth) {
vnode.child.disabled = false
} else {
vnode.child.disabled = true
}
})
}
})
注冊完指令之后組件中需要用到的地方就直接嵌套el-tootip
加上v-tip
就可以了就不需要在每個組件里寫重復的代碼了
<el-tooltip v-tip placement="top" :content="title">
<span>{{title}}</span>
</el-tooltip>