废话不多说直接上代码
封装源码
<template>
<div class="text-tooltip" :style="{ width: width }">
<el-tooltip class="item" effect="dark" :disabled="isShowTooltip" :content="content" placement="top">
<p class="over-flow" :class="className" @mouseover="onMouseOver(refName)">
<span :ref="refName">{{ content || '-' }}</span>
<!-- <slot></slot> -->
</p>
</el-tooltip>
</div>
</template>
<script>
export default {
name: 'textTooltip',
props: {
// 显示的文字内容
content: {
type: String,
default: () => {
return ''
},
},
// 外层框的样式,在传入的这个类名中设置文字显示的宽度
className: {
type: String,
default: () => {
return ''
},
},
// 为页面文字标识(如在同一页面中调用多次组件,此参数不可重复)
refName: {
type: String,
default: () => {
return ''
},
},
// 定义项目宽度
width: {
type: String,
default: () => ''
}
},
data() {
return {
isShowTooltip: true,
}
},
methods: {
onMouseOver(str) {
if (!this.$refs[str] || !this.$refs[str].parentNode) return false
this.$nextTick(() => {
let parentWidth = this.$refs[str].parentNode.offsetWidth
let contentWidth = this.$refs[str].offsetWidth
// 判断是否开启tooltip功能
this.isShowTooltip = contentWidth <= parentWidth
})
},
},
}
</script>
<style lang="scss" scoped>
.over-flow {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.wid10 {
width: 10%;
}
p {
margin: 0;
}
</style>
组件调用
<my-tooltip :content="factories[formData.factoryName] " width="70%" ref-name="cusTooltip1" />