[element-ui] 表格el-table表头固定自适应高度解决方案_自适应高度

flex布局

<body>
<div id="app" class="flex-c">
<div class="header flex-s">头部导航</div>
<div class="content flex-a flex">
<div class="left flex-s">左部菜单</div>
<div class="right flex-a flex-c">
<div class="menu-list flex-s">表格菜单</div>
<div class="table-container flex-a" ref="container">自适应区域</div>
<div class="pagination flex-s">表格分页</div>
</div>
</div>
</div>
</body>
html {
height: 100%;
}

body {
height: 100%;
margin: 0;
}

#app {
height: 100%;
text-align: center;
}

.flex, .flex-c { display: flex }
.flex-c { flex-direction: column; }
.flex-a { flex: auto; }
.flex-s { flex-shrink: 0; }

动态计算表格高度

我们把表格插入到自适应区域,并将设置自适应区域为相对定位,表格容器设置为绝对定位:

<div class="table-container flex-a" ref="container">
<div class="table-container-inner">
<el-table
:data="tableData"
:height="tableHeight"
border>
</el-table>
</div>
</div>
.table-container {
position: relative;
}

.table-container-inner {
position: absolute;
left: 0;
right: 0;
top: 0
}

然后我们使用Element.getBoundingClientRect()这个接口来获取自适应区域的高度,设置为表格高度,这样即可达到自适应高度固定表头的效果

export default {
data () {
return {
tableHeight: 0,
tableData: [
// xxx 表格数据
]
}
},
mounted () {
this.calHeight()
},
methods: {
calHeight () {
this.$nextTick(() => {
const rect = this.$refs.container.getBoundingClientRect()
this.tableHeight = rect.height
})
}
}
}

当然,在用户操作的过程中,免不了会有一些影响页面布局的因素,此时我们需要重新计算一次高度。其中最常见的一种操作是改变浏览器窗口的大小,我们可以通过监听resize事件来重新计算高度:

data () {
return {
timer: 0
}
}
mounted () {
// ...
window.addEventListener('resize', this.onResize)
},
beforeDestroy () {
this.timer && clearTimeout(this.timer)Z
window.removeEventListener('resize', this.onResize)
},
methods: {
// ...
onResize () {
this.timer && clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.calHeight()
}, 500)
}
}

为了避免resize高频触发回调,这里使用定时器进行一个简单的控制。完整例子可以查看:​​http://jsrun.net/v56Kp/edit​


​[ElementUI] 表格el-table表头固定自适应高度解决方案​