- el-table固定头部要加hight属性,这个hight要动态获取并动态计算
<div class="table-container" ref="container">
<el-table :data="tableData" :height="tableHeight" >
<el-table-column v-for="item in tableHeadData" :key="item.prop" :prop="item.prop" :label="item.label">
</el-table-column>
</el-table>
</div>
.table-container {
box-sizing: border-box;
height: calc(100vh - 350px); //我当前项目是不能超出一屏,所以这句不是必要的
margin: 24px 0 40px; //设置表格的外边距
}
-
使用
**Element.getBoundingClientRect()**获取自适应区域的高度,设置为表格高度,这样即可达到自适应高度固定表头的效果。 -
当改变浏览器窗口的大小,通过监听resize事件来重新计算高度
export default {
data () {
return {
tableHeight: 0,
tableData: []
}
},
methods: {
calcHeight () { //动态计算表格高度
this.$nextTick(() => {
if(this.$refs.container) return //防止由于拿不到container元素无法调用getBoundingClientRect而报错
this.tableHeight = this.$refs.container.getBoundingClientRect().height
})
},
onResize () {//防抖处理
this.timer && clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.calcHeight()
}, 500)
}
},
mounted () {
this.calcHeight()
window.addEventListener('resize', this.onResize)//监听页面重绘事件
},
beforeDestroy () { //跳转页面的时候移除重绘事件监听
this.timer && clearTimeout(this.timer)
window.removeEventListener('resize', this.onResize)
},
}