需求:当页面搜索区域元素高度发生改变时,内容区域表格的高度自动调整高度,以及当页面缩放时,表格高度也随之改变。
demo效果图:
代码:
<template>
<!-- 注意: ref="pagePanel" 整体页面-->
<div class="pages" ref="pagePanel">
<!-- 注意: ref="contentPanel" 内部区域 -->
<div class="pages-content" ref="contentPanel">
<!-- 注意: btnPanel 操作栏高度-->
<div ref="btnPanel">
<el-button @click="listnum = 10">展开</el-button>
</div>
<!-- 注意: tableMaxHeight 表格高度-->
<el-table :data="tableData" :height="tableMaxHeight" border style="width: 100%">
<el-table-column prop="date" label="日期" width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180">
</el-table-column>
<el-table-column prop="address" label="地址">
</el-table-column>
</el-table>
<!-- 注意: ref="paginationPanel 分页" -->
<el-pagination ref="paginationPanel" layout="prev, pager, next" :total="50">
</el-pagination>
</div>
<!-- 注意: ref="searchPage" 搜索 -->
<div class="pages-search" ref="searchPage">
<el-button @click="listnum = 10">展开</el-button>
<el-button @click="listnum = 5">关闭</el-button>
<div v-for="item in listnum">
{{ item }}
</div>
</div>
</div>
</template>
<script>
//模拟表格数据
const tableData = [];
for (let i = 0; i < 100; i++) {
tableData.push({
date: i,
name: `Edrward ${i}`,
address: `London Park no. ${i}`,
});
}
export default {
data() {
return {
listnum: 5,
tableData,
tableMaxHeight: 500//默认高度可为0
}
},
created() { },
mounted() {
this.$nextTick(() => {
// 初始化表格高度
const contentPanel = this.$refs.contentPanel.clientHeight;
const paginationPanelHeight = this.$refs.paginationPanel ? 32 : 0
const btnPanelHeight = this.$refs.btnPanel?.clientHeight || 0//操作栏高度
console.log(btnPanelHeight);
this.tableMaxHeight = contentPanel - paginationPanelHeight - btnPanelHeight - 50
window.addEventListener('resize', this.getHeight);//页面缩放
})
},
beforeDestroy() {
window.removeEventListener('resize', this.getHeight);
},
updated() {
//页面元素高度改变触发从事件
this.getHeight()
},
methods: {
getHeight() {
const pagePanelHeight = this.$refs.pagePanel.clientHeight;//整个页面高度
const searchPageHeight = this.$refs.searchPage.clientHeight;//底部搜索高度
const paginationPanelHeight = this.$refs.paginationPanel ? 32 : 0//分页高度
const btnPanelHeight = this.$refs.btnPanel?.clientHeight || 0//操作栏高度
// 表格高度
this.tableMaxHeight =
pagePanelHeight -
searchPageHeight -
btnPanelHeight -
paginationPanelHeight - 50;//50 是margin或者padding高度,可自行调整
}
}
}
</script>
<style lang="less" scoped>
.pages {
display: flex;
flex-direction: column;
//height: calc(100vh - 100px);
height:100%;
padding: 10px;
box-sizing: border-box;
.pages-header {
background: white;
border-radius: 10px;
}
.pages-content {
background: white;
border-radius: 10px;
flex: 1;
margin: 10px 0;
}
.pages-search {
background-color: white;
border-radius: 10px;
}
}
</style>