友友们,你们是否总被要求el-tooltip自适应显示所困扰,觉得写那些判断很麻烦?那就收藏这篇文章吧,有需要的时候直接copy过去就好了。
注意:我用的vue3,环境不对的友友请自适应格式,哈哈。
子组件:Tooltip.vue
<script setup name="Tooltip">
import { ref, onMounted, nextTick } from 'vue'
const props = defineProps({
content: {
type: String,
default: ''
}
})
const isShowTooltip = ref(false)
const boxRef = ref(null)
const contentRef = ref(null)
onMounted(() => {
nextTick(() => {
isShowTooltip.value = contentRef.value.offsetWidth >= boxRef.value.offsetWidth
})
})
</script>
<template>
<div class="w-full h-full ellipsis" ref="boxRef">
<el-tooltip effect="dark" :content="content" placement="top-start" :disabled="!isShowTooltip">
<span ref="contentRef">{{ content }}</span>
</el-tooltip>
</div>
</template>
<style scoped lang="scss">
.ellipsis { // 省略号三要素
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
父组件应用
<span style="width: 200px;overflow: hidden;">
<Tooltip :content="这是一段很长的文字。。。。。。" />
</span>
未成功的友友请查看两点:
1.打印查看offsetWidth,看看是否符合显示条件
2.可能样式还需要调整,请微调