背景(高度自适应)
- el-table 是一个非常很好用的组件,但是
表格太高
的话,就会导致左右的滑动块 在最下面,每次滑动都要滑到最下面去,很不方便
- 愿景: 希望 表格高度根据页面的
视口高度
,来调整表格高度,多余的部分支持上下滑动条
实现
- 基于原生的js来实现
- 定义一个高度自适应的方法
- 先获取元素到
视口底部
的距离表格自适应高度 = 元素到底部的高度 - 分页器的高度
//表格高度自适应
getHeight() {
let getHeightFromBottom = (element, variableHeight) => {
const elementRect = element.getBoundingClientRect().top;
const windowHeight = window.innerHeight;
const elementHeightFromBottom = windowHeight - elementRect;
const result = elementHeightFromBottom - variableHeight;
return result;
}
const element = document.getElementById('dataTable');
const variableHeight = 70; // 给定的变量高度 一般留于分页器高度
this.autoHeight =getHeightFromBottom(element, variableHeight) ;
},
使用
给一个id 用于 定位
- 在元素上定义
id="dataTable"
,用于 获取自适应高度
<el-table :height="autoHeight" id="dataTable" ref="dataTable" show-summary :summary-method="getSummaries" v-loading="loading" :data="mixPlanWastageList" @selection-change="handleSelectionChange" border>
在钩子函数中延迟调用此方法
- 在页面挂载的钩子函数的执行这个方法
- 但是
延迟调用
,等到页面第一次渲染完毕之后
再自适应高度
mounted() {
this.$nextTick(() => {
this.getList()
this.getHeight()
})
},
新需求:当查询出来的行数足够多的时候,使用高度自适应,行数比较少的时候显示全部行数即可,不用自适应了
- 新定义一个方法:根据当前行数计算表格高度
比较 计算高度 和 自适应高度,表格的高度取两者间的最小值
// 根据行数计算表格高度
handleCurrentChange() {
this.$nextTick(() => {
const rows = this.$refs.dataTable.$el.querySelectorAll('.el-table__row');
// 表格高度 = (行高 * 数据长度 ) + 表头高度 + 分页器高度
if (this.mixPlanWastageList.length == 0){
this.calculateTableHeight = this.paginationHeight + 70;
}else {
let headHeight = this.$refs.dataTable.$el.querySelector('.el-table__header-wrapper').clientHeight;
this.calculateTableHeight = rows[0].clientHeight * this.mixPlanWastageList.length + headHeight + this.paginationHeight;
}
});
},
此方法的调用时机:
- 在updated的钩子函数中调用,页面发生变化就会调用
- 在自适应高度计算完毕之后调用
updated() {
this.$nextTick(() =>{
// 重新渲染表格 防止表格变形
this.$refs.dataTable.doLayout();
// 最后一次渲染表格后,自动滚动到最右边
this.scrollRight()
})
this.handleCurrentChange()
},
表格高度取用
计算数据
即可
computed: {
// 计算表格高度
tableHeight() {
// 行数高度和自适应高度取最小值
return Math.min(this.autoHeight, this.calculateTableHeight)
}
},
<el-table :height="tableHeight" >
参考链接
https://blog.csdn.net/weixin_56796650/article/details/138652341