我要固定高度当只有一条数据时保持固定高度 当数据超出时滚动
时间: 2024-02-17 08:09:10 浏览: 14
你可以尝试以下代码来实现这个需求:
```html
<template>
<div class="table-container" :style="{ height: tableHeight }">
<a-table :columns="columns" :data-source="data" :scroll="{ y: scrollHeight }"></a-table>
</div>
</template>
<script>
export default {
data() {
return {
tableHeight: '240px',
scrollHeight: 'auto',
columns: [...],
data: [...]
}
},
mounted() {
this.setTableHeight();
window.addEventListener('resize', this.setTableHeight);
},
beforeDestroy() {
window.removeEventListener('resize', this.setTableHeight);
},
methods: {
setTableHeight() {
const tableContainer = this.$el.querySelector('.table-container');
const tableHeader = tableContainer.querySelector('.ant-table-header');
const tableBody = tableContainer.querySelector('.ant-table-body');
const tablePagination = tableContainer.querySelector('.ant-pagination');
const minHeight = 240; // 最小高度
const maxHeight = 480; // 最大高度
const totalHeight = tableHeader.offsetHeight + tableBody.offsetHeight + tablePagination.offsetHeight;
if (totalHeight <= minHeight) {
this.tableHeight = `${minHeight}px`;
this.scrollHeight = 'auto';
} else if (totalHeight > maxHeight) {
this.tableHeight = `${maxHeight}px`;
this.scrollHeight = `${maxHeight - tableHeader.offsetHeight - tablePagination.offsetHeight}px`;
} else {
this.tableHeight = `${totalHeight}px`;
this.scrollHeight = `${tableBody.offsetHeight}px`;
}
}
}
}
</script>
<style scoped>
.table-container {
overflow: auto;
}
</style>
```
这里通过在 `mounted` 钩子中调用 `setTableHeight` 方法来动态计算表格高度,并在窗口大小发生变化时重新计算表格高度。在 `setTableHeight` 方法中,先获取表格容器、表格头、表格体和分页器的高度,然后根据这些高度来计算表格的最小高度、最大高度和当前高度,并设置给 `tableHeight` 和 `scrollHeight` 变量,最后在模板中使用 `tableHeight` 来设置表格容器的高度以及使用 `scrollHeight` 来设置表格体的滚动高度。当表格总高度小于等于最小高度时,表格容器的高度为最小高度,表格体不需要滚动;当表格总高度超过最大高度时,表格容器的高度为最大高度,表格体需要滚动;否则表格容器的高度为表格总高度,表格体不需要滚动。