一、实现思路
根据当前屏幕的可视高度(window.innerHeight) - 表格顶部距离可视高度顶部的距离 = 剩余高度 (可适当手动添加底部安全距离(bottomPadding))
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
/**
* 获取表格最大高度
* @param options
* @returns {{tableRef: null, setTableHeight: setTableHeight, tableHeight: Ref<UnwrapRef<number>>}}
*/
export function useTableHeight(options = {}) {
const { tableRef: externalTableRef = null, hasPagination = true } = options
const internalTableRef = ref(null)
const tableRef = externalTableRef || internalTableRef
const maxHeight = ref(0)
const calculateTableHeight = () => {
if (!tableRef.value) return
const windowHeight = window.innerHeight
const tableTop = tableRef.value.$el.getBoundingClientRect().top
const bottomPadding = hasPagination ? 68 : 20
return windowHeight - tableTop - bottomPadding
}
const setTableHeight = () => {
nextTick(() => {
maxHeight.value = calculateTableHeight()
})
}
onMounted(() => {
window.addEventListener('resize', setTableHeight)
})
onUnmounted(() => {
window.removeEventListener('resize', setTableHeight)
})
// 监听 tableRef 的变化
watch(
() => tableRef.value,
(newVal) => {
if (newVal && newVal.$el) {
setTableHeight()
}
},
{ immediate: true }
)
// 提供手动触发方法
const updateTableHeight = () => {
nextTick(setTableHeight)
}
return {
tableRef,
maxHeight,
setTableHeight,
updateTableHeight
}
}
使用
const { tableRef, maxHeight } = useTableHeight()
<el-table
ref="tableRef"
v-loading="loading"
:data="tableData"
:max-height="maxHeight"
:summary-method="getSummaries"
border
show-summary
stripe> ...