实现文本溢出省略与 Tooltip 提示的组件
组件核心功能场景
- 文本溢出时自动显示省略号并激活 Tooltip
- 表格内场景:无论文本是否溢出,操作图标始终保持可见
组件代码
javascript
<template>
<div class="flex items-center">
<el-tooltip :disabled="!isOverflow" :content="text" placement="top">
<span
ref="textRef"
class="ellipsis-text"
:style="[{ maxWidth }, textStyle]"
@mouseenter="checkOverflow"
>
{{ text }}
</span>
</el-tooltip>
<div class="ml-1 flex items-center">
<slot name="icon" />
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue';
const props = defineProps({
text: {
type: String,
default: '',
},
maxWidth: {
type: String,
default: '128px',
},
textStyle: Object
});
const textRef = ref(null);
const isOverflow = ref(false);
const checkOverflow = () => {
const el = textRef.value;
if (!el) return;
isOverflow.value = el.scrollWidth > el.clientWidth;
};
onMounted(checkOverflow);
watch(() => props.text, checkOverflow);
</script>
<style scoped>
.ellipsis-text {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
line-height: 26px;
}
</style>
使用场景与示例
表格列应用
html
[
......,
{
label: 'AccessKey',
width: 270,
showOverflowTooltip: false,
disableEllipsis: true,
render: (scoped) => (
<TextWithIcon text={scoped.row.accessKey} maxWidth="240px">
{{
icon: () => (
<Icon
icon="ep:document-copy"
size={16}
style={{ color: 'var(--aq-color-primary)', cursor: 'pointer' }}
class="ml-1 mr-2px"
onClick={() => handleCommand(scoped.row.accessKey)}
/>
),
}}
</TextWithIcon>
),
},
]
表单详情页应用
html
<template>
<TextWithIcon :text="item.content" maxWidth="224px"></TextWithIcon>
</template>
实现逻辑
比较机制
- 通过比较元素的
scrollWidth和clientWidth判断是否溢出 - 在组件挂载、文本内容变化时自动重新检测
- 使用
nextTick确保 DOM 更新后执行检测
触发条件
- 仅在鼠标悬停时检测溢出状态
- 动态控制 Tooltip 的禁用状态
- 避免不必要的 DOM 操作和事件监听
扩展性
- 通过插槽支持自定义图标
- 支持传入自定义样式对象
- 可配置最大宽度参数