组件模板
<template>
<el-tooltip placement="top" :disabled="!title">
<div slot="content">{{ title }}</div>
<span
ref="overflowTooltip"
class="overflow-tooltip"
:style="{ maxWidth: maxWidth }"
>
{{ content }}
</span>
</el-tooltip>
</template>
组件样式
<style scoped>
.overflow-tooltip {
display: inline-block;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
line-height: inherit;
vertical-align: middle;
}
</style>
组件逻辑
export default {
props: {
content: [String, Number, Boolean],
maxWidth: {
type: String
}
},
data() {
return {
title: ''
}
},
watch: {
content() {
this.$nextTick(this.getContentTitle)
}
},
mounted() {
this.getContentTitle()
},
methods: {
getContentTitle() {
const el = this.$refs.overflowTooltip
const elComputed = document.defaultView.getComputedStyle(el, '')
const padding =
parseInt(elComputed.paddingLeft.replace('px', '')) +
parseInt(elComputed.paddingRight.replace('px', ''))
const range = document.createRange()
range.setStart(el, 0)
range.setEnd(el, el.childNodes.length)
const rangeWidth = range.getBoundingClientRect().width
if (
rangeWidth + padding > el.offsetWidth ||
el.scrollWidth > el.offsetWidth
) {
this.title = this.content
}
}
}
}