赋予element Tooltip组件 文字超出隐藏时才展示tip的能力
照着element源码抄
专业版
- 注意:el-tooltip组件并没有在插槽外面有div,若使用插槽没元素包裹就裸了
- 封装
<template>
<el-tooltip v-bind="$attrs"
:disabled="!isShow"
@mouseover.native="mouseover">
<div class="tooltip-main"
ref="$toolTip">
<slot></slot>
</div>
</el-tooltip>
</template>
<script>
/**
* --------------- 说明 ---------------
* 该组件是为了让内部文字长度超出隐藏时再显示tooltip
* 比较div和内部slot替换后的span的宽度 判断文字是否溢出
*/
export default {
name: 'ToolTip',
inheritAttrs: false,
data() {
return {
isShow: false,
}
},
mounted() {},
methods: {
mouseover() {
const ctrllArea = this.$refs.$toolTip
const range = document.createRange()
range.setStart(ctrllArea, 0)
range.setEnd(ctrllArea, ctrllArea.childNodes.length)
const innerW = range.getBoundingClientRect().width
const ctrlW = ctrllArea.getBoundingClientRect().width
this.isShow = innerW > ctrlW
},
},
}
</script>
<style lang="scss" scoped>
.tooltip-main {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
- 使用
<ToolTip effect="dark"
class="tip-name"
:content="item.name"
placement="top-start">
{{ item.name }}
</ToolTip>
.tip-name {
width: 174px;
text-align: left;
}
简约版
- 封装
<template>
<el-tooltip v-bind="$attrs"
:disabled="disabled"
@mouseover.native="mouseover">
<div class="tooltip-main"
ref="$toolTip">
<span>
<slot></slot>
</span>
</div>
</el-tooltip>
</template>
<script>
/**
* --------------- 说明 ---------------
* 该组件是为了让内部文字长度超出隐藏时再显示tooltip
* 比较div和内部slot替换后的span的宽度 判断文字是否溢出
*/
export default {
name: 'ToolTip',
inheritAttrs: false,
data() {
return {
disabled: true,
}
},
mounted() {},
methods: {
mouseover() {
let dom = this.$refs.$toolTip
let core = dom.children[0]
// 等号是为了防止加了省略号后元素宽度和不加省略号的元素宽度一致,导致不显示tooltip
if (dom.offsetWidth <= core.offsetWidth) {
// 说明文字溢出了 显示tooltip
this.disabled = false
}
},
},
}
</script>
<style lang="scss" scoped>
.tooltip-main {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
- 使用
<ToolTip effect="dark"
class="tip-name"
:content="item.name"
placement="top-start">
{{ item.name }}
</ToolTip>
.tip-name {
width: 174px;
text-align: left;
}