vue+element-ui表格最大高度适配解决方案

第一步:utils目录下创建一个文件为directive,新建auto-height.js文件,

  1. export default {
  2. componentUpdated(el, binding, vnode) {
  3. const ctx = vnode.context;
  4. if (!ctx || typeof ctx[binding.arg] === 'undefined' || ctx.autoHeightResizeListenner) return;
  5. ctx.autoHeightResizeListenner = () => {
  6. let top = el.offsetTop;
  7. let cur = el.offsetParent;
  8. while(cur !== null) {
  9. top += cur.offsetTop;
  10. cur = cur.offsetParent;
  11. }
  12. const h = (window.innerHeight - top) + binding.value;
  13. ctx[binding.arg] = Math.max(h, 100 );
  14. };
  15. window.addEventListener('resize', ctx.autoHeightResizeListener, false);
  16. setTimeout(ctx.autoHeightResizeListenner, 50);
  17. },
  18. unbind(el, binding, vnode){
  19. const ctx = vnode.context;
  20. if(ctx && ctx.autoHeightResizeListener) {
  21. window.removeEventListener('resize', ctx.autoHeightResizeListener, false);
  22. ctx.autoHeightResizeListener = null;
  23. }
  24. },
  25. };

第二步:全局配置 在main.js中导入 auto-height.js文件

  1. import autoHeight from './utils/directive/auto-height';
  2. Vue.directive('auto-height',autoHeight)

第三步:组件中需要的标签添加两个属性 v-auto-height:maxHeight = ‘-10’ :max-height=”maxHeight”

  1. <el-table v-auto-height:maxHeight = '-10' :max-height="maxHeight"></el-table>