效果图
1.文字过长显示省略号
可以用css设置 常用的3个属性 注意要设置宽度
<template>
<div class="content" :style="{width: props.width}">
{{props.content}}
</div>
</template>
<script setup>
const props = defineProps({
content: { type: String, default: "" },
width: { type: String, default: "" },
})
</script>
<style>
.content {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis
}
</style>
2.鼠标移入显示提示框
鼠标移入显示提示框可以自己写一个, 也一个直接用组件。 这里直接用element中的el-tooltip组件。
<template>
<el-tooltip
effect="dark"
:content="props.content"
placement="top"
>
<div class="content" :style="{width: props.width}">
{{props.content}}
</div>
</el-tooltip>
</template>
<script setup >
const props = defineProps({
content: { type: String, default: "" },
width: { type: String, default: "" },
})
</script>
<style>
.content {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis
}
</style>
3.自动判断文字长度是否显示提示框
判断内容的宽度是否超过了父级容器的宽度
<template>
<el-tooltip
effect="dark"
:content="props.content"
placement="top"
:disabled="isShow"
>
<div class="content" :style="{width: props.width}" @mouseover="isShowTooltip">
<span ref="contentRef">{{props.content}}</span>
</div>
</el-tooltip>
</template>
<script setup >
import { ref } from 'vue'
const props = defineProps({
content: { type: String, default: "" },
width: { type: String, default: "" },
})
// 使用isShow来控制tooltip是否显示
let isShow = ref(true)
// 在span标签上定义一个ref
const contentRef = ref()
//鼠标移入容器的时候进行判断
const isShowTooltip = function () {
if(contentRef.value.parentNode.offsetWidth > contentRef.value.offsetWidth) {
isShow.value = true
} else {
isShow.value = false
}
}
</script>
<style>
.content {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis
}
</style>
4.更多扩展可以使用solt, 进行自定义显示tooltip内容, 也可以显示非文本内容
<template>
<el-tooltip
effect="dark"
:content="props.tooltipContent ? props.tooltipContent : props.content"
placement="top"
:disabled="isShow"
>
<template #content>
<!-- 此处的默认值先看tooltipContent有没有,没有就给默认content -->
<slot name="tooltipContent">{{props.tooltipContent ? props.tooltipContent : props.content}}</slot>
</template>
<div class="content" :style="{width: props.width}" @mouseover="isShowTooltip">
<span ref="contentRef">
<!-- 给一个没有写插槽的默认值,兼容纯文本的情况 -->
<slot name="content">{{props.content}}</slot>
</span>
</div>
</el-tooltip>
</template>