vue指令v-autoHeight 实现 el-table 高度自适应

101 阅读1分钟

使用指令, 默认100% 可以自定义减去

  • directive.js
// 自定义指令
export const autoHeight = {
  // 指令第一次绑定到元素
  bind: function (el, binding, vnode, oldVnode) {},
  // 绑定元素插入父节点
  inserted: function (el, binding) {
    const parentH = el.parentElement.offsetHeight;
    const val = binding.value || 0;
    if (parentH) {
      const h = parentH - Number(val);
      el.style.height = h + 'px';
    }
  },
};
  • main.js
import Vue from 'vue';
import { autoHeight } from './utils/directive';

Vue.directive('autoHeight', autoHeight);

new Vue({
  el: '#app',
  render: h => h(App),
});
  • 使用

<el-table :max-height="tableH" v-autoHeight:height="autoH"></>

<script>
export default {
  methods: {
    getHeight() {
      this.$nextTick(() => {
        if (this.$refs.tableBoxRef) {
          const h = this.$refs.tableBoxRef.clientHeight;
          this.tableH = h;
        }
      });
    },
  },
  computed: {
    autoH: function () {
      if (this.showPagination) {
        return 120;
      } else {
        return 80;
      }
    },
  },
  mounted() {
    this.getHeight();
  },
}
</script>