el-tooltip 根据长度自适应换行以及显隐
环境
vue: "3.2.37"
element-ui: "2.1.8"
要求
- tooltip 根据内容自动换行
- 如果内容超出显示省略号显示,不超出不显示 tooltip
代码
组件
<template>
<el-tooltip
v-bind="$attrs"
:content="content"
:disabled="showTooltip"
:append-to="toolDom"
:effect="effect"
:placement="placement"
>
<div ref="toolDom" @mouseover="onMouseOver(content)">
<slot />
</div>
</el-tooltip>
</template>
<script setup>
const toolDom = ref()
const showTooltip = ref(true)
const tooltipWidth = ref(0)
defineProps({
content: {
type: String,
default: ''
},
effect: {
type: String,
default: 'dark'
},
placement: {
type: String,
default: 'top'
}
})
function findParent(node) {
if (node.className === 'el-tooltip__trigger') {
return node
} else {
return findParent(node.parentNode)
}
}
function onMouseOver() {
const tag = toolDom.value
const parentWidth = findParent(tag).offsetWidth
const contentWidth = tag.children[0].offsetWidth
showTooltip.value = contentWidth < parentWidth
tooltipWidth.value = parentWidth + 'px'
}
</script>
<style lang="scss" scoped>
::v-deep .el-popper {
max-width: v-bind(tooltipWidth);
}
</style>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
使用
<div style="width: 100px; overflow: hidden">
<tooltip :content="'我是內容很長的一個內容'">
<div class="text-ellipsis" style="max-width: fit-content">我是內容很長的一個內容</div>
</tooltip>
</div>
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
效果

