文本溢出省略并Tooltip组件在表单和表格内的使用

实现文本溢出省略与 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>

实现逻辑

比较机制

  • 通过比较元素的 scrollWidthclientWidth 判断是否溢出
  • 在组件挂载、文本内容变化时自动重新检测
  • 使用 nextTick 确保 DOM 更新后执行检测

触发条件

  • 仅在鼠标悬停时检测溢出状态
  • 动态控制 Tooltip 的禁用状态
  • 避免不必要的 DOM 操作和事件监听

扩展性

  • 通过插槽支持自定义图标
  • 支持传入自定义样式对象
  • 可配置最大宽度参数
相关推荐
千寻girling2 小时前
《 MongoDB 教程 》—— 不可多得的 MongoDB
前端·后端·面试
攀登的牵牛花2 小时前
前端向架构突围系列 - 状态数据设计 [8 - 3]:服务端状态与客户端状态的架构分离
前端
掘金安东尼2 小时前
⏰前端周刊第 452 期(2026年2月2日-2月8日)
前端·javascript·github
古茗前端团队2 小时前
业务方上压力了,前端仔速通RGB转CMYK
前端
ArkPppp3 小时前
NestJS全栈实战笔记:优雅处理 Entity 与 DTO 的映射与字段过滤
javascript·nestjs
广州华水科技3 小时前
单北斗变形监测一体机在基础设施安全与地质灾害监测中的应用价值分析
前端
钟智强3 小时前
React2Shell:CVE-2025-66478 Next.js 远程执行漏洞深度分析与代码剖析
开发语言·javascript·ecmascript
Dragon Wu3 小时前
Electron Forge集成React Typescript完整步骤
前端·javascript·react.js·typescript·electron·reactjs
芳草萋萋鹦鹉洲哦3 小时前
【Tailwind】动画解读:Tailwind CSS Animation Examples
前端·css
华仔啊3 小时前
jQuery 4.0 发布,IE 终于被放弃了
前端·javascript