本组件是对 Element UI 中 el-tooltip 组件的二次封装
新增特性:鼠标移入父节点时,根据内容是否溢出判断是否显示 Tooltip
el-tooltip 文档
<template>
<!--
属性
content:el-tooltip 属性,文本内容
effect:el-tooltip 属性,Tooltip 主题,默认 light
placement:el-tooltip 属性,Tooltip 显示的方向,默认值为 top
-->
<el-tooltip :disabled="disabled" :content="content" :effect="effect" :placement="placement">
<span class="j-tooltip" ref="content">{{content}}</span>
</el-tooltip>
</template>
<script>
export default {
name: 'JTooltip',
props: {
content: String,
effect: {
type: String,
default: 'light'
},
placement: {
type: String,
default: 'top'
}
},
data() {
return {
disabled: false
}
},
mounted() {
const parentNode = this.$refs.content.parentNode;
parentNode.addEventListener('mouseenter', this.handleMouseenter);
},
methods: {
handleMouseenter(e) {
this.disabled = !this.textOverflow(e.target);
},
textOverflow(element) {
const range = document.createRange();
range.setStart(element, 0);
range.setEnd(element, element.childNodes.length);
const rangeWidth = range.getBoundingClientRect().width;
const computed = window.getComputedStyle(element)
const padding = (parseInt(computed.paddingLeft, 10) || 0) + (parseInt(computed.paddingRight, 10) || 0);
return rangeWidth + padding > element.offsetWidth || element.scrollWidth > element.offsetWidth;
},
},
beforeDestroy() {
const parentNode = this.$refs.content.parentNode;
if (parentNode) {
parentNode.removeEventListener('mouseenter', this.handleMouseenter);
}
},
}
</script>
<style lang="scss" scoped>
.j-tooltip {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
</style>
|