文本溢出省略并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 操作和事件监听

扩展性

  • 通过插槽支持自定义图标
  • 支持传入自定义样式对象
  • 可配置最大宽度参数
相关推荐
代码搬运媛8 小时前
Jest 测试框架详解与实现指南
前端
counterxing9 小时前
我把 Codex 里的 Skills 做成了一个 MCP,还支持分享
前端·agent·ai编程
wangqiaowq9 小时前
windows下nginx的安装
linux·服务器·前端
之歆9 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
发现一只大呆瓜9 小时前
Vite凭什么这么快?3分钟带你彻底搞懂 Vite 热更新的幕后黑手
前端·面试·vite
Maimai108089 小时前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
candyTong10 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
kyriewen11 小时前
产品经理把PRD写成“天书”,我用AI半小时重写了一遍,他当场愣住
前端·ai编程·cursor
humcomm12 小时前
元框架的工作原理详解
前端·前端框架
canonical_entropy12 小时前
Attractor Before Harness: AI 大规模开发的方法论
前端·aigc·ai编程