注册全局指令
import tableHeight from './directive/tableHeight';
Vue.use(tableHeight);
页面结构
- CC+CV开发者必须遵循结构
- 高级开发者可根据情况更改指令代码,不必遵循
<template>
<div class="mian">
<div class="search"></div>
<div class="table-box">
<el-table :height="height" v-table-height="setTableHeight"> </el-table>
</div>
<el-pagination></el-pagination>
</div>
</template>
用法
<el-table
:height="height"
v-table-height="setTableHeight"
>
----------------------
data() {
return {
height: '300'
};
}
----------------------
methods: {
setTableHeight(height) {
this.$nextTick(()=>{
this.height = height;
});
}
}
----------------------
<style lang="scss">
.main {
height: 100%;
}
</style>
源码
function calcHeight(el, binding) {
const parentNode = el.parentNode
const CSSStyleDeclaration = getComputedStyle(parentNode.parentNode)
let {marginBottom, marginTop, paddingBottom, paddingTop} = CSSStyleDeclaration
marginBottom = Number.parseInt(marginBottom, 10)
marginTop = Number.parseInt(marginTop, 10)
paddingBottom = Number.parseInt(paddingBottom, 10)
paddingTop = Number.parseInt(paddingTop, 10)
const otherH = marginBottom + marginTop + paddingBottom + paddingTop
const totalH = parentNode.parentNode.clientHeight
const searchH = parentNode.previousSibling ? parentNode.previousSibling.clientHeight : 0
const paginationH = parentNode.nextSibling ? parentNode.nextSibling.clientHeight : 0
const calcH = totalH - searchH - paginationH - otherH
if (binding.value) {
binding.value(calcH)
}
// 不能直接修改表格高度,使用回调传递高度
// el.style = `height:${calcH || 300}px
}
const tableHeight = {
inserted: function(el, binding, vnode, oldVnode) {
el.tempCalcHeight = calcHeight
el.tempCalcHeight(el, binding)
window.onresize = ()=>{
el.tempCalcHeight(el, binding)
}
},
unbind: function(el) {
window.onresize = null
delete el.tempCalcHeight
}
}
const install = function(Vue) {
Vue.directive('tableHeight', tableHeight)
}
if (window.Vue) {
window.permit = tableHeight
Vue.use(install)
}
tableHeight.install = install
export default tableHeight