先回顾一下vue2+element-ui的策略
export default (config) => {
const {
subtractHeight = 250,
} = config;
return {
data() {
return {
subtractHeight,
// 列表高度
tableHeight: `${document.body.clientHeight - this.subtractHeight}px`,
};
},
created() {
window.addEventListener('resize', this.getHeight);
// 监听事件注销,防止内存溢出
this.$once('hook:beforeDestory', () => {
window.removeEventListener('resize', this.getHeight);
});
},
mounted() {
this.getHeight();
},
watch: {
subtractHeight: {
handler() {
this.getHeight();
},
},
},
methods: {
/**
* @todo 获取列表高度
*/
getHeight() {
this.tableHeight = `${document.body.clientHeight - this.subtractHeight}px`;
},
},
};
};
vue3 就翻译一下吧
// tableHeight.js
import { ref, onBeforeUnmount, nextTick } from "vue";
import _ from "lodash";
export default function (opts) {
const {
subtractHeight = 500,
} = opts;
const tableHeight= ref(500)
// 计算高度
const getHeight = _.debounce(function() {
const height = document.body.clientHeight - subtractHeight
tableHeight.value = height > 200 ? height : 200;
}, 500)
// 监听窗口变化,触发高度计算
window.addEventListener('resize', getHeight);
onBeforeUnmount(() => {
window.removeEventListener('resize', getHeight);
})
// 初始化高度
nextTick(()=>{
getHeight()
})
return {
tableHeight
};
}
页面中使用
<template>
<el-table :data="tableData" style="width: 100%" :max-height="tableHeight">
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" label="Address" />
</el-table>
</template>
<script setup>
import mixTableHeight from './tableHeight.js'
const { tableHeight } = mixTableHeight({ subtractHeight: 380 })
</script>