el-table header固定body高度自适应并滚动
elementui官方给出的header固定body滚动方案仅需给height属性赋值,但当我们遇到并不能写死height的情况,或许你会抛弃height,通过css使整个表格高度自适应并滚动,但表头也会被滚上去,就很不优雅。这时你可能会想到通过:show-header="false"隐藏表头并在上方另写一表通过配置css仅显示该表的表头,曲线救国,实现表头固定表体高度自适应并滚动(实际上,这是我 灵机一动 想到的,也确实这么做了,也不是不行,就是写起来蛮怪的是🙆♂️)。
我们只需依赖 getBoundingClientRect 动态赋值el-table的height。
参考:ElementUI表格el-table表头固定自适应高度解决方案
<el-table
:data="tableData"
:height="tableHeight">
</el-table>
记得data里加tableHeight,给父容器加上ref=“tableContainer”
data() {
return {
tableHeight: null, // Null或者先给个默认的大小
timer: 0
}
},
mounted() {
this.calHeight()
window.addEventListener('resize', this.onResize)
},
beforeDestroy() {
this.timer && clearTimeout(this.timer)
window.removeEventListener('resize', this.onResize)
},
methods: {
// 根据父元素高度改变表格高度
calHeight() {
this.$nextTick(() => {
// Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置
const rect = this.$refs.tableContainer.getBoundingClientRect()
// this.tableHeight = rect.height - 24 // 若有分页,减去分页高度
this.tableHeight = rect.height
})
},
// 监听界面resize调calHeight更新表格高度
onResize() {
this.timer && clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.calHeight()
}, 100)
},
}

当使用ElementUI的el-table组件时,遇到无法预设固定高度但需要表头固定的情况,官方的高度设置可能不适用。一种解决办法是通过CSS实现表格整体自适应高度并滚动,但这会导致表头滚动。另一种方法是隐藏原表头,手动创建表头,虽然可行但编写繁琐。本文介绍一种更简洁的方法,利用getBoundingClientRect动态设置el-table的height,达到表头固定且表体自适应高度的效果。记得在data中添加tableHeight属性,并为父容器添加ref=“tableContainer”。
1174

被折叠的 条评论
为什么被折叠?



