1.需求
pc端开发的时候,比如有个盒子需要跟着屏幕的高度变化而变化,那么就需要设置他的高度
这个只适用于一个页面只有一个盒子内容时,比如整个页面只有一个表格
2.实现
在template中,以设置穿梭框的高度为例
<div>
<span>选择收件角色</span>
<el-transfer
:titles="['所有角色', '已选角色']"
filterable
:filter-method="filterMethod"
filter-placeholder="请输入用户"
v-model="reseveValue"
:data="data"
:style="{height: transferHeight + 'px'}">
</el-transfer>
</div>
此时我这个transferHeight高度变量不需要在data中声明,直接在computed中声明即可,自己调高度,减去上面【长江5号】盒子所占用的高度即可
computed: {
transferHeight: function () {
return window.innerHeight - 330
}
},
用法和created、mounted、watch、methods放在同级即可
然后就可以啦,上面这种只适合于一个页面只有一张表的,如果有表单也有表格呢?
3.如果页面中还有其他内容时,对盒子表格的高度进行自适应,如果页面还有其他内容,表格高度就高,如果没有其他盒子,表格高度就高。
那么就需要用页面高度 - 表格的高度
template中
<el-table
ref="singleTable"
:data="tableData"
:height="tableHeight + 'px'"
border
highlight-current-row
style="width: 100%"
>
<el-table-column
width="80"
type="index"
label="序号"
align="center">
</el-table-column>
<el-table-column
:show-overflow-tooltip="true"
prop="name"
label="名称"
align="center"
>
</el-table-column>
</el-table>
在data中
data () {
tableHeight: 0
}
在mounted中
mounted: function () {
this.$nextTick(() => {
this.tableHeight = this.getTreeHeight(this.$refs['singleTable'].$el) - 50;
})
},
在methods中
// 计算高度
getTreeHeight (dom) {
return window.innerHeight - dom.offsetTop;
},
这样就完成了在页面中如果加了东西,表格高度就低,如果页面少了东西,表格高度就高