Element UI 的扩展功能
1. el-tooltip 超出宽度显示文字提示,否则隐藏
需求
- 设置固定宽度;
- 文字超出宽度,用...显示;
- 鼠标悬停到文字上,用el-tooltip显示全部文字内容;如果文字未超出宽度,el-tooltip隐藏。
解决方法
- 第一步:鼠标悬停后显示的内容
- 第二步:关闭文字提示功能,el-tooltip 的 disabled 属性
- 第三步:鼠标移入事件,@mouseover="onMouseOver(name)"
- 获取元素父级可视宽度:tag.parentNode.offsetWidth
- 获取元素可视宽度:tag.offsetWidth
- 内容超出,显示文字提示内容:contentWidth > parentWidth
- 第四步:绑定ref
完整代码
<template>
<el-tooltip
ref="tlp"
:content="content"
effect="dark"
:disabled="tooltipFlag"
:placement="placement"
>
<div class="tooltip" @mouseover="onMouseOver('name')">
<span ref="name">{{ content ? content : "-" }}</span>
</div>
</el-tooltip>
</template>
<script>
export default {
name: "EllipsisTooltip",
props: {
content: {
type: String,
default: ""
}, // 字符内容
placement: {
type: String,
default: "top"
}
},
data() {
return {
tooltipFlag: false
}
},
methods: {
onMouseOver(str) {
const tag = this.$refs[str];
if (tag) {
const parentWidth = tag.parentNode.offsetWidth; // 获取元素父级可视宽度
const contentWidth = tag.offsetWidth; // 获取元素可视宽度
this.tooltipFlag = contentWidth <= parentWidth;
}
}
}
};
</script>
<style>
.tooltip {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
然后在用的地方使用组件
<EllipsisTooltip :content="这里是需要展示的所以文字内容"></EllipsisTooltip>