之前有写到如何通过自定义指令的方式在vue2项目中实现对element-ui表格的自适应高度,在这里不多赘述vue2和vue3自定义指令写法有何不同,直接抛代码,如若有该需求,可直接复制到项目中使用

又是熟悉的adaptive.js文件,具体用法可转至vue element table表格高度自适应查看

import ResizeObserver from "resize-observer-polyfill";

const isServer = typeof window === "undefined";

/* istanbul ignore next */
const resizeHandler = function (entries) {
  for (let entry of entries) {
    const listeners = entry.target.__resizeListeners__ || [];
    if (listeners.length) {
      listeners.forEach((fn) => {
        fn();
      });
    }
  }
};

/* istanbul ignore next */
export const addResizeListener = function (element, fn) {
  if (isServer) {
    return;
  }
  if (!element.__resizeListeners__) {
    element.__resizeListeners__ = [];
    element.__ro__ = new ResizeObserver(resizeHandler);
    element.__ro__.observe(element);
  }
  element.__resizeListeners__.push(fn);
};

/* istanbul ignore next */
export const removeResizeListener = function (element, fn) {
  if (!element || !element.__resizeListeners__) {
    return;
  }
  element.__resizeListeners__.splice(
    element.__resizeListeners__.indexOf(fn),
    1
  );
  if (!element.__resizeListeners__.length) {
    element.__ro__.disconnect();
  }
};
/**
 * How to use
 * <el-table height="100px" v-el-height-adaptive-table="{bottomOffset: 30}">...</el-table>
 * el-table height is must be set
 *  bottomOffset: 30(default)   // The height of the table from the bottom of the page.
 */

const doResize = (el, binding, vnode) => {
  const { el: $table } = vnode;

  const { value } = binding;
  if (!value.fixedHeader) {
    return;
  }
  const bottomOffset = (value && value.bottomOffset) || 70;
  if (!$table) {
    return;
  }

  const layout = document.getElementById("app");
  setTimeout(() => {
    const height =
      window.innerHeight - el.getBoundingClientRect().top - bottomOffset;
    const layoutHeight = layout.clientHeight;
    layoutHeight > 810
      ? (layout.style.minHeight = "810px")
      : (layout.style.minHeight = "auto");
    $table.style.height = height + 'px';
    // $table.doLayout();
  }, 600);
};

export default {
  beforeMount(el, binding, vnode) {
    el.resizeListener = () => {
      doResize(el, binding, vnode);
    };

    addResizeListener(window.document.body, el.resizeListener);
  },
  mounted(el, binding, vnode) {
    doResize(el, binding, vnode);
  },
  unmounted(el) {
    const layout = document.getElementById("app");
    layout.style.minHeight = "810px";
    removeResizeListener(window.document.body, el.resizeListener);
  },
};

Logo

前往低代码交流专区

更多推荐