项目需求:需要给超出的文本加提示,没超出的不加提示,这里我使用的是 el-tooltip 组件。el-tooltip 组件本身就是悬浮提示功能,所以对组件进行了二次封装(下面代码可以直接复制使用,哈哈)。
注意。这里主要是用了 el-tooltip 组件的disabled属性。
<template>
<el-tooltip :effect="effect" :content="text" :placement="placement" :disabled="isShowTooltip">
<div : @mouseover="onMouseOver">
<span ref="ellipsis">{{ text }}</span>
</div>
</el-tooltip>
</template>
<script>
export default {
props: {
placement: {
type: String,
default: 'right-start',
},
text: {
type: String,
default: '',
},
effect: {
type: String,
default: 'dark',
},
className: { type: String, default: '' },
},
data() {
return {
isShowTooltip: false,
};
},
created() {},
methods: {
onMouseOver() {
let parentWidth = this.$refs['ellipsis'].parentNode.offsetWidth; // 获取元素父级可视宽度
let contentWidth = this.$refs['ellipsis'].offsetWidth; // 获取元素可视宽度
this.isShowTooltip = contentWidth <= parentWidth;
},
},
};
</script>
<style scoped lang="less">
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
然后在需要用到组件的页面中引入。
使用:
<tool-tip
:text="-前端博客-前端教程-记录 web 前端开发的个人技术博客"
:placement="'left'"
>
</tool-tip>