真香系列:vue table 自动计算高度指令

163 阅读1分钟

注册全局指令

// main.js 里面
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); // eslint-disable-line
}
tableHeight.install = install;
export default tableHeight;