外观
Vue 3 表格组件:长文本展开的 TdPopover
表格里的备注、名称、说明,长度经常不固定。全部换行会让一行变得很高,只显示省略号又看不到完整内容。
我把这类展示收进了 TdPopover:平时保持单行,文字放不下时,点击单元格展开完整内容。短文字直接显示,也可以通过插槽放入自定义详情。
这篇用同一段备注说明使用前后的区别,再记录组件内部怎样判断溢出、定位浮层和处理关闭。
一、使用前:只能看到省略后的文字
在 Vue 3 页面里,给文字容器设置宽度,再加上单行省略样式:
vue
<script setup>
const remark = '客户希望在工作日下午联系,周末不方便接听;确认需求后,需要补充发送产品说明,并记录下一次回访时间。'
</script>
<template>
<div class="remark-cell">{{ remark }}</div>
</template>
<style scoped>
.remark-cell {
width: 200px;
box-sizing: border-box;
padding: 10px 12px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>页面只显示这段备注的开头,后面变成省略号。点击它也没有变化,因为这些 CSS 只处理显示,页面还没有提供查看完整内容的操作。
要补上展开功能,还需要判断文字是否放得下、记录打开状态、放置浮层,并处理点击外部关闭。每个表格列都单独写一遍,重复的部分就适合收进组件。
二、使用后:点击长文字展开完整内容
1. 保存组件并安装定位依赖
本文的组件可以单独放进 Vue 3 项目。先在下面的 demo 中点击“下载组件源码”,保存为 TdPopover.vue,放到使用页面旁边,再安装浮层定位库:
sh
pnpm add @floating-ui/vue这份可复用版本保留了溢出检测、点击展开、浮层定位和两个插槽。显示文字与滚动区域使用原生元素,样式也写在组件内,复制时不需要连同业务组件和全局表格样式一起搬过去。
2. 把原来的文字容器换成组件
vue
<script setup>
import { ref } from 'vue'
import TdPopover from './TdPopover.vue'
const remark = ref('客户希望在工作日下午联系,周末不方便接听;确认需求后,需要补充发送产品说明,并记录下一次回访时间。')
</script>
<template>
<div style="width: 200px">
<TdPopover :label="remark" />
</div>
</template>页面仍提供备注和容器宽度,省略样式与展开操作交给组件。首次显示时,组件测量文字:放得下就正常显示,放不下就显示省略号,并允许点击展开。
点击后,浮层以缩放和淡入动画展开,宽度与触发区域一致。完整文字可以换行,超过 200px 高度的部分可以滚动查看。点击外部、右上角关闭按钮,或者按 Esc,浮层会以相反的动画收起。
3. 放进表格列的 render 中
如果列表使用 Naive UI,可以在已有页面的列定义中这样接入。下面是列定义的节选,row.remark 来自该行数据:
js
import { h } from 'vue'
import TdPopover from './TdPopover.vue'
const columns = [
{
title: '备注',
key: 'remark',
width: 200,
render(row) {
return h(TdPopover, { label: row.remark })
},
},
]这里用 h 创建组件,不需要另外配置 JSX。表格负责列宽和行数据,TdPopover 接收这一行的文本,并在自己的容器里测量。列宽变化后,组件会重新判断是否需要展开。
三、demo:对照省略与展开
左侧只有省略样式,右侧使用 TdPopover。点击右侧长文字查看完整备注;修改上方的内容或列宽,可以观察组件重新判断后的结果。“查看联系信息”则演示自定义详情。
| 操作 | 使用前 | 使用后 |
|---|---|---|
| 显示长备注 | 显示省略号 | 显示省略号,并允许点击展开 |
| 点击长备注 | 没有展开操作 | 显示完整内容,可以换行和滚动 |
| 显示“林晓”或数字 0 | 直接显示 | 直接显示,默认不弹出浮层 |
| 将长文字改短,或增加列宽 | 浏览器重新计算省略效果 | 同时重新判断溢出,放得下时关闭浮层 |
| 查看其他详情 | 页面另外写一套浮层 | 用 trigger 和 popover 插槽提供内容 |
四、参数和插槽怎么用
| 名称 | 用途 | 默认值 |
|---|---|---|
label | 普通文本内容,支持字符串、数字和空值 | '' |
showPopover | 是否始终允许点击展开 | false |
trigger 插槽 | 替换单元格里的触发内容 | 显示 label |
popover 插槽 | 替换展开后的内容 | 显示完整的 label |
showPopover 为 true 表示允许展开,仍然需要点击才会打开。 例如“查看联系信息”很短,通常不会溢出,但点击后要展示另一份详情,就需要启用这个参数:
vue
<TdPopover show-popover>
<template #trigger>
<span>查看联系信息 ↗</span>
</template>
<template #popover>
<div>林晓 · 联系信息</div>
<div>联系时间:工作日 14:00—17:00</div>
<div>联系渠道:邮件</div>
</template>
</TdPopover>trigger 决定单元格里显示什么,popover 决定展开后显示什么。自定义触发内容没有默认文字节点供组件测量,因此这个用法显式传入 show-popover,由页面决定它可以打开。
五、组件内部怎样完成展开
1. 分开记录“允许展开”和“已经打开”
js
const show = ref(false)
const isOverflow = ref(false)
const canOpen = computed(() => props.showPopover || isOverflow.value)
function openPopover() {
if (!canOpen.value) return
show.value = true
}isOverflow 保存测量结果,canOpen 决定点击有没有作用,show 保存当前浮层是否打开。它们分开以后,短文字可以正常显示,自定义详情也能通过 showPopover 允许展开。
2. 比较文字宽度与容器可用宽度
默认文字节点是一个不换行的 span,负责单行省略。它的 scrollWidth 表示内容需要的宽度,即使部分文字已经被裁掉,也能读到超出的宽度。测量时,再从外层容器宽度里扣掉左右 padding,得到留给文字的可用宽度。
例如容器宽 200px,左右 padding 各 12px,留给文字的宽度就是 176px。文字自然宽度如果是 360px,就已经放不下,需要允许展开。
测量发生在 nextTick() 之后,保证读取的是 Vue 更新后的 DOM。组件用 ResizeObserver 监听容器和文字尺寸,用 watch 监听 label 变化。列宽、文本或字体尺寸发生变化时,会更新测量结果;如果文字已经放得下,也会关闭已打开的浮层。
3. Teleport 改变位置,Floating UI 计算坐标
表格经常带有滚动容器。如果浮层仍放在单元格内部,容易被 overflow: hidden 或 overflow: auto 裁掉。
组件用 Teleport 把浮层挂到 body 下,让它离开表格的裁剪范围。但移到 body 以后,它还需要知道应该出现在哪个单元格旁边,这部分交给 Floating UI:
js
useFloating(referenceRef, floatingRef, {
transform: false,
placement: 'bottom-start',
middleware: [offset(({ rects }) => -rects.reference.height), flip()],
whileElementsMounted: (reference, floating, updatePosition) =>
autoUpdate(reference, floating, updatePosition, { animationFrame: true }),
})referenceRef 指向单元格中的触发区域,floatingRef 指向浮层。bottom-start 先把浮层左边对齐触发区域左边,放到它的下方;负的 offset 再向上移动一个触发区域的高度,让完整文字从单元格所在位置展开。
flip() 处理靠近可视区域边缘时的位置翻转,autoUpdate() 在滚动、尺寸变化或触发区域移动时更新坐标。它返回清理函数,浮层移除时,useFloating 会调用这个函数停止监听。
Teleport 负责把浮层放到哪里,Floating UI 负责算出浮层的坐标。单独使用 Teleport,浮层并不会自动跟着单元格定位。
4. 关闭浮层并清理监听
组件检查点击位置是否落在触发区域或浮层内部,点击其他位置时关闭。触发单元格大部分离开可视区域,也会通过 IntersectionObserver 关闭它对应的浮层。
卸载组件时,断开尺寸和可见性观察器,移除文档上的点击、键盘事件。这样切换页面、移除表格行以后,不会继续保留这些监听。
5. 用 Transition 保留展开与收起动画
浮层用 Vue 的 Transition 包起来,由内部元素的 v-if 控制打开状态:
vue
<Teleport to="body">
<Transition name="td-popover-scale" appear>
<div v-if="show" class="td-popover-content">
<!-- 浮层内容,完整写法见文末源码。 -->
</div>
</Transition>
</Teleport>打开时,透明度从 0 变成 1,大小从 scale(0.9) 变成 scale(1),持续 0.3 秒;关闭时反向执行。浮层在单元格上方展开时,缩放起点设为左下角,在下方时设为左上角,让动画从靠近触发位置的一侧开始。
v-if 放在浮层元素上,Teleport 和 Transition 保持挂载。这样关闭时,Vue 可以先执行离场动画,再移除浮层;如果直接卸载外层 Teleport,浮层会立即消失。
定位配置保留 transform: false,让 Floating UI 通过 top、left 定位,CSS 的 transform 则用于缩放,避免两者覆盖同一个属性。
六、使用时要留意的地方
文字必须有受限的容器宽度,才能产生省略效果。表格里由列宽约束;单独放在 flex 或 grid 中时,注意给容器设置宽度或 min-width: 0,避免容器被长文字撑开。
label 为数字 0 时应正常显示,不能直接用 label || '—' 判断空值。本文版本把空字符串和 null 显示成“—”,其他字符串通过 Vue 文本插值显示。
如果页面要显示的是自定义按钮、标签或复杂详情,就使用插槽并显式设置 show-popover。组件管理展开和关闭,详情里的业务内容仍由页面提供。
完整组件收藏
demo 使用的组件与下面展示的是同一份源码,可以在 demo 底部直接下载。复制到其他 Vue 3 项目时,安装 @floating-ui/vue,再根据页面位置调整导入路径。
查看完整 TdPopover.vue
vue
<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref, useId, watch } from 'vue'
import { autoUpdate, flip, offset, useFloating } from '@floating-ui/vue'
const props = withDefaults(defineProps<{
label?: string | number | null
showPopover?: boolean
}>(), { label: '', showPopover: false })
const referenceRef = ref<HTMLElement | null>(null)
const referenceContentRef = ref<HTMLElement | null>(null)
const floatingRef = ref<HTMLElement | null>(null)
const show = ref(false)
const isOverflow = ref(false)
const contentWidth = ref(0)
const contentId = useId()
const displayLabel = computed(() => props.label === null || props.label === '' ? '—' : String(props.label))
// showPopover 控制是否允许展开;show 才是当前打开状态。
const canOpen = computed(() => props.showPopover || isOverflow.value)
const { floatingStyles, update, placement } = useFloating(referenceRef, floatingRef, {
transform: false,
placement: 'bottom-start',
// 将浮层往上移一行,从单元格所在位置展开完整文字。
middleware: [offset(({ rects }) => -rects.reference.height), flip()],
whileElementsMounted: (reference, floating, updatePosition) =>
autoUpdate(reference, floating, updatePosition, { animationFrame: true }),
})
const floatingContentStyle = computed(() => ({
...floatingStyles.value,
width: `${contentWidth.value}px`,
transformOrigin: placement.value.startsWith('top') ? 'bottom left' : 'top left',
}))
/** 测量文字自然宽度和容器可用宽度,同时同步浮层宽度。 */
async function updateMeasurements() {
await nextTick()
const reference = referenceRef.value
if (!reference) return
const style = window.getComputedStyle(reference)
const padding = (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0)
const availableWidth = reference.clientWidth - padding
const textWidth = referenceContentRef.value?.scrollWidth ?? 0
isOverflow.value = textWidth > availableWidth + 1
contentWidth.value = reference.getBoundingClientRect().width
if (!canOpen.value) show.value = false
if (show.value) void update()
}
/** 只有允许展开时,点击或键盘操作才会打开浮层。 */
function openPopover() {
if (!canOpen.value) return
show.value = true
}
function closePopover() {
show.value = false
}
function handleOutsidePointer(event: PointerEvent) {
const target = event.target as Node | null
if (target && !referenceRef.value?.contains(target) && !floatingRef.value?.contains(target)) {
closePopover()
}
}
function handleEscape(event: KeyboardEvent) {
if (event.key !== 'Escape' || !show.value) return
closePopover()
referenceRef.value?.focus({ preventScroll: true })
}
let resizeObserver: ResizeObserver | undefined
let intersectionObserver: IntersectionObserver | undefined
onMounted(() => {
void updateMeasurements()
resizeObserver = new ResizeObserver(() => { void updateMeasurements() })
if (referenceRef.value) resizeObserver.observe(referenceRef.value)
if (referenceContentRef.value) resizeObserver.observe(referenceContentRef.value)
intersectionObserver = new IntersectionObserver(([entry]) => {
// 触发单元格大部分离开可视区域时,关闭它对应的浮层。
if (!entry.isIntersecting || entry.intersectionRatio < 0.5) closePopover()
}, { threshold: [0, 0.5] })
if (referenceRef.value) intersectionObserver.observe(referenceRef.value)
document.addEventListener('pointerdown', handleOutsidePointer, true)
document.addEventListener('keydown', handleEscape)
})
watch(() => [props.label, props.showPopover], () => { void updateMeasurements() }, { flush: 'post' })
onUnmounted(() => {
resizeObserver?.disconnect()
intersectionObserver?.disconnect()
document.removeEventListener('pointerdown', handleOutsidePointer, true)
document.removeEventListener('keydown', handleEscape)
// useFloating 在元素移除时执行 autoUpdate 返回的清理函数。
})
</script>
<template>
<div
ref="referenceRef"
class="td-label-ellipsis"
:class="{ 'td-label-ellipsis--interactive': canOpen }"
:role="canOpen ? 'button' : undefined"
:tabindex="canOpen ? 0 : undefined"
:aria-expanded="canOpen ? show : undefined"
:aria-controls="show ? contentId : undefined"
@click="openPopover"
@keydown.enter.prevent="openPopover"
@keydown.space.prevent="openPopover"
>
<slot name="trigger">
<span ref="referenceContentRef" class="td-label">{{ displayLabel }}</span>
</slot>
</div>
<Teleport to="body">
<Transition name="td-popover-scale" appear>
<div
v-if="show"
:id="contentId"
ref="floatingRef"
class="td-popover-content"
:style="floatingContentStyle"
role="dialog"
aria-label="完整内容"
>
<div class="td-popover-header">
<span>完整内容</span>
<button type="button" aria-label="关闭完整内容" @click="closePopover">×</button>
</div>
<div class="td-popover-body">
<slot name="popover">{{ displayLabel }}</slot>
</div>
</div>
</Transition>
</Teleport>
</template>
<style scoped>
.td-label-ellipsis {
width: 100%;
min-width: 0;
box-sizing: border-box;
padding: 10px 12px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
cursor: default;
font: inherit;
}
.td-label-ellipsis--interactive { cursor: pointer; }
.td-label-ellipsis--interactive:hover { background: var(--vp-c-bg-soft, #f1f5f9); }
.td-label-ellipsis:focus-visible { outline: 2px solid var(--vp-c-text-2, #64748b); outline-offset: -2px; }
.td-label { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.td-popover-content {
position: absolute;
z-index: 9999;
max-width: calc(100vw - 24px);
box-sizing: border-box;
border: 1px solid var(--vp-c-divider, #cbd5e1);
border-radius: 8px;
color: var(--vp-c-text-1, #1e293b);
background: var(--vp-c-bg-elv, #fff);
box-shadow: 0 8px 24px rgb(0 0 0 / 18%);
font: 14px/1.7 var(--vp-font-family-base, sans-serif);
}
.td-popover-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 8px 4px 12px;
color: var(--vp-c-text-2, #64748b);
font-size: 12px;
}
.td-popover-header button {
width: 24px;
height: 24px;
border: 0;
border-radius: 4px;
color: inherit;
background: transparent;
font: 20px/1 sans-serif;
cursor: pointer;
}
.td-popover-header button:hover { background: var(--vp-c-bg-soft, #f1f5f9); }
.td-popover-body {
max-height: 200px;
overflow: auto;
padding: 0 12px 12px;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.td-popover-scale-enter-active,
.td-popover-scale-leave-active {
transition: opacity 0.3s ease, transform 0.3s ease;
}
.td-popover-scale-enter-from,
.td-popover-scale-leave-to {
opacity: 0;
transform: scale(0.9);
}
.td-popover-scale-enter-to,
.td-popover-scale-leave-from {
opacity: 1;
transform: scale(1);
}
.td-popover-scale-leave-active { pointer-events: none; }
@media (prefers-reduced-motion: reduce) {
.td-popover-scale-enter-active,
.td-popover-scale-leave-active { transition-duration: 0.01ms; }
}
</style>这份封装让我在写表格列时只需要传入文本,或提供详情插槽。文字是否溢出、浮层坐标和关闭操作集中到组件里,页面继续处理行数据和业务展示。