1. antdv表格根据scroll里y的值来控制表格高度,当内容超出y值后表格就会出现滚动条。需要为表格的y提供一个会随浏览器高度变化而变化的参数,窗口越小表格允许展现的高度也越小,例子中是由updateYHeight计算属性来控制的。
<a-table
:columns="columns"
:data-source="data"
:scroll="{ x: true, y: updateYHeight }"
:pagination="pagination"
@change="handleTableChange"
>
2. 给表格的外层容器添加ref,方便监听外层容器的高度,从而改变表格的高度。
注意:
- 外层容器高度需要能够随浏览器高度变化而变化
- 可以给最外层容器的高度设为100vh,其中的表格外层盒子高度设为90%,就可以使表格外层容器的高度随浏览器高度变化而变化了
- 总之就是最外层盒是固定值,中层的表格外层盒用百分比%设置高度,最里层的表格高度根据中层的高度设置
<div class="bottom" ref="tableBox">
<a-table
:columns="columns"
:data-source="data"
:scroll="{ x: true, y: updateYHeight }"
:pagination="pagination"
@change="handleTableChange"
></a-table>
</div>
3. 在data中设置一个名为tableBoxHeight的属性值来存放外层容器高度,初始值为0,在html完成渲染后在mounted中获取表格外层盒子的高度作为tableBoxHeight的属性值,并注册一个监听浏览器变化的事件,一变化就重置tableBoxHeight的属性值。通过计算属性得到最终需要的表格的高度值。
注意:
- this.tableBoxHeight- 175中的175不是固定的,根据自己的需要设置
- 记得在unmounted中解除监听,避免影响其他页面(vue3是unmounted,vue2是destroyed)
data() {
return {
tableBoxHeight: 0,
};
},
mounted() {
this.tableBoxHeight = this.$refs.tableBox.clientHeight;
window.addEventListener("resize", this.renewTableBoxHeight);
},
unmounted() {
window.removeEventListener("resize", this.renewTableBoxHeight);
},
methods: {
renewTableBoxHeight() {
this.tableBoxHeight = this.$refs.tableBox.clientHeight;
},
},
computed: {
updateYHeight() {
return this.tableBoxHeight- 175;
},
},
提示:element的表格是一样的原理,element的表格是把updateYHeight的值赋给max-height。
<el-table :data="tableData" style="width: 100%" :max-height="updateYHeight">