refactor(useTableScroll): 重构表格滚动高度计算逻辑,适配表头高度扣除

1.  优化滚动高度计算方式,改为容器总高减去表头和分页器高度,计算更准确
2.  新增nextTick等待DOM渲染完成后再进行尺寸测量
3.  调整默认最小高度为100px,优化变量命名和注释
4.  简化菜单页面的模板代码格式,统一代码风格
5.  更新useTableScroll的调用参数,移除旧的自定义paginationHeight传参
This commit is contained in:
andyesfly committed 2026-08-21 19:59:22 +08:00
1 parent 4048aeb6fb
commit 026ec34471
2 files changed
+66 -90

No files matched your search

+23 -16
View File
@@ -1,49 +1,56 @@
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
/**
* 监听表格父容器高度,动态计算 a-table 的 scroll.y。
* 自动测量 a-table 内部的分页器高度,从而得到准确的 tbody 高度。
* 正确计算 AntDV a-table 的 scroll.y 高度。
* 核心逻辑:scroll.y = 外层容器总高 - 表头真实高度 - 分页器真实高度
*/
export function useTableScroll(minHeight = 120) {
export function useTableScroll(minHeight = 100) {
const wrapperRef = ref<HTMLElement | null>(null);
const tableHeight = ref<number>(minHeight);
let observer: ResizeObserver | null = null;
function update() {
if (!wrapperRef.value) return;
const wrapperHeight = wrapperRef.value.clientHeight;
// 动态获取分页器高度(如果存在)
// 动态获取表头和分页器的真实高度
const headerEl = wrapperRef.value.querySelector('.ant-table-thead') as HTMLElement | null;
const paginationEl = wrapperRef.value.querySelector('.ant-table-pagination') as HTMLElement | null;
const headerHeight = headerEl ? headerEl.offsetHeight : 55; // 55 为兜底
const paginationHeight = paginationEl ? paginationEl.offsetHeight : 0;
// scroll.y = 容器总高 - 分页器高度(表头由 a-table 自动固定,无需扣除)
const tbodyHeight = wrapperHeight - paginationHeight;
// 计算 tbody 的高度
const tbodyHeight = wrapperHeight - headerHeight - paginationHeight;
tableHeight.value = Math.max(tbodyHeight, minHeight);
}
onMounted(() => {
onMounted(async () => {
if (!wrapperRef.value) return;
// 等待 DOM 渲染完成后再测量
await nextTick();
observer = new ResizeObserver(update);
observer.observe(wrapperRef.value);
// 初始测量
// 初始计算
update();
// MutationObserver 用于监听分页器的动态添加/移除
// 使用 MutationObserver 监听 DOM 变化(比如数据加载后表头/分页器出现)
const mutationObserver = new MutationObserver(() => {
update();
});
mutationObserver.observe(wrapperRef.value, { childList: true, subtree: true });
// 保存以便卸载时使用
(wrapperRef.value as any).__mutationObserver = mutationObserver;
(wrapperRef.value as any).__mo = mutationObserver;
});
onBeforeUnmount(() => {
observer?.disconnect();
observer = null;
if (wrapperRef.value && (wrapperRef.value as any).__mutationObserver) {
(wrapperRef.value as any).__mutationObserver.disconnect();
if (wrapperRef.value && (wrapperRef.value as any).__mo) {
(wrapperRef.value as any).__mo.disconnect();
}
});