front/src/composables/useTableContainerHeight.ts
2026-03-23 10:00:44 +08:00

51 lines
1.3 KiB
TypeScript

import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
export function useTableContainerHeight() {
const tableContainerRef = ref<HTMLElement | null>(null);
const tableHeight = ref(0);
let resizeObserver: ResizeObserver | null = null;
const updateHeight = () => {
tableHeight.value = Math.max(0, tableContainerRef.value?.clientHeight || 0);
};
const observe = (el: HTMLElement | null) => {
if (!resizeObserver || !el) return;
resizeObserver.observe(el);
};
const unobserve = (el: HTMLElement | null) => {
if (!resizeObserver || !el) return;
try {
resizeObserver.unobserve(el);
} catch (_) {}
};
onMounted(() => {
resizeObserver = new ResizeObserver(() => updateHeight());
observe(tableContainerRef.value);
window.addEventListener('resize', updateHeight);
nextTick(updateHeight);
});
watch(tableContainerRef, (nextEl, prevEl) => {
unobserve(prevEl);
observe(nextEl);
nextTick(updateHeight);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', updateHeight);
if (resizeObserver) {
unobserve(tableContainerRef.value);
resizeObserver.disconnect();
resizeObserver = null;
}
});
return {
tableContainerRef,
tableHeight,
};
}