🔥 TextTipsPlus 多行省略 + Tooltip 提示组件
✅ 功能亮点
功能 | 说明 |
---|
多行省略 | 通过 line-clamp 控制显示行数,默认单行 |
动态宽度 | 支持传入 width (数值或百分比/字符串) |
Tooltip 超出显示 | 自动判断是否超出容器,超出后显示完整 tooltip |
插槽支持 | 支持插入复杂结构(文本、图标、HTML 等) |
i18n 支持 | 插槽和 text 均可支持 $t() |
🧱 组件源码(TextTipsPlus.vue)
<template>
<div ref="containerRef" class="text-tips-plus" :style="{ width: computedWidth }">
<el-tooltip
v-if="showTooltip"
effect="dark"
placement="top-start"
:content="tooltipContent"
>
<div ref="textRef" class="text-content" :class="[`clamp-${lineClamp}`]">
<slot>{{ $t(text) }}</slot>
</div>
</el-tooltip>
<div
v-else
ref="textRef"
class="text-content"
:class="[`clamp-${lineClamp}`]"
>
<slot>{{ $t(text) }}</slot>
</div>
</div>
</template>
<script setup>
import { ref, watchEffect, onMounted, computed } from 'vue'
const props = defineProps({
text: String,
width: {
type: [Number, String],
default: '100%'
},
lineClamp: {
type: Number,
default: 1 // 默认单行
}
})
const containerRef = ref(null)
const textRef = ref(null)
const showTooltip = ref(false)
const computedWidth = computed(() => {
return typeof props.width === 'number' ? `${props.width}px` : props.width
})
const tooltipContent = computed(() => {
return props.text || textRef.value?.innerText || ''
})
onMounted(() => {
checkOverflow()
window.addEventListener('resize', checkOverflow)
})
watchEffect(() => {
checkOverflow()
})
function checkOverflow() {
if (textRef.value && containerRef.value) {
const isOverflow =
textRef.value.scrollHeight > containerRef.value.clientHeight ||
textRef.value.scrollWidth > containerRef.value.clientWidth
showTooltip.value = isOverflow
}
}
</script>
<style lang="scss" scoped>
.text-tips-plus {
display: inline-block;
vertical-align: top;
line-height: 1.5;
overflow: hidden;
}
.text-content {
overflow: hidden;
word-break: break-word;
display: -webkit-box;
-webkit-box-orient: vertical;
// 单行时的 fallback
text-overflow: ellipsis;
}
.clamp-1 {
-webkit-line-clamp: 1;
}
.clamp-2 {
-webkit-line-clamp: 2;
}
.clamp-3 {
-webkit-line-clamp: 3;
}
.clamp-4 {
-webkit-line-clamp: 4;
}
</style>
🚀 使用示例
✅ 1. 默认单行省略(支持多语言)
<TextTipsPlus text="this_is_a_very_long_key" />
✅ 2. 自定义宽度、多行省略
<TextTipsPlus text="内容较长..." :width="200" :lineClamp="2" />
✅ 3. 使用插槽展示复杂结构(如图标 + 文本)
<TextTipsPlus :lineClamp="2" :width="'300px'">
<i class="el-icon-info" style="margin-right: 4px"></i>
这是用户的说明内容,超过一定长度会自动省略。
</TextTipsPlus>
📚 Props & Slots
Props
名称 | 类型 | 默认值 | 说明 | |
---|
text | string | '' | 要展示的文本(支持 $t) | |
width | `number | string` | 100% | 内容区域宽度 |
lineClamp | number | 1 | 展示行数,自动省略 | |
Slots
名称 | 说明 |
---|
default | 自定义内容,优先于 text |
🧩 扩展建议
可扩展项 | 说明 |
---|
鼠标移入延迟展示 Tooltip | 使用 :open-delay="300" 等参数 |
Tooltip 支持插槽 | 通过自定义 tooltip 插槽支持富文本 |
行数更多样 | 可通过动态 class 或变量生成 .clamp-N |