自我摸索,如有BUG,欢迎指正修改。货不多说,直接源码。
<template>
<div ref="textBoxRef" class="text-tips">
<el-tooltip
v-if="ellipsis"
class="box-item"
effect="dark"
:content="$t(text)"
placement="top-start">
<span ref="textRef">{{ $t(text) }}</span>
</el-tooltip>
<span ref="textRef" v-else>{{ $t(text) }}</span>
</div>
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue'
const props = defineProps({
text: {
type: String,
required: true
}
})
const textBoxRef = ref(null)
const textRef = ref(null)
const ellipsis = ref(false)
onMounted(() => {
textBoxRef.value.parentNode.style.display = 'flex';
textBoxRef.value.parentNode.style.alignItems = 'center';
textBoxRef.value.parentNode.style.justifyContent = 'center';
// 绑定一个鼠标移入事件
textBoxRef.value.parentNode.addEventListener('mouseenter', () => {
if (textRef.value.scrollWidth > textBoxRef.value.clientWidth) {
ellipsis.value = true
} else {
ellipsis.value = false
}
})
})
</script>
<style lang="scss" scoped>
.text-tips {
max-width: calc(100% - 15px);
display: inline-flex;
justify-content: center;
align-items: flex-start;
overflow: hidden;
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
</style>
这是封装的组件,可以是直接引用的。