// hooks/useTableHeight.js
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
export default function useTableHeight() {
const tableHeight = ref(0)
const searchRef: any = ref(null)
const tableRef: any = ref(null)
const btnRef: any = ref(null)
const updateTableHeight = () => {
nextTick(() => {
if (!searchRef.value) return
const windowHeight = window.innerHeight
const searchHeight = searchRef.value.$el?.offsetHeight || searchRef.value.offsetHeight
let btnHeight = 0
if (btnRef.value) {
btnHeight = btnRef.value.$el?.offsetHeight || btnRef.value.offsetHeight
}
tableHeight.value = windowHeight - searchHeight - btnHeight - 270;
})
}
onMounted(() => {
updateTableHeight()
window.addEventListener('resize', updateTableHeight)
})
onUnmounted(() => {
window.removeEventListener('resize', updateTableHeight)
})
return {
tableHeight,
searchRef,
tableRef,
btnRef,
updateTableHeight
}
}
页面中的使用,给各个ref对应到对应的div上
<template>
<div class="sjk">
<div class="search" ref="searchRef">
// 查询条件
</div>
<div class="content">
<div class="top" ref="btnRef">
// 按钮
</div>
<div class="bottom" ref="tableRef">
// 表格
</div>
</div>
</div>
</template>
<script lang="ts" setup>
const newTableHeight = ref(0);
const { tableHeight, tableRef, btnRef, searchRef, updateTableHeight } = useTableHeight();
watch(
tableHeight,
(newVal) => {
newTableHeight.value = newVal;
},
{ immediate: true }
);
const updateHeight = () => {
updateTableHeight();
};
</script>