Yuliang-Lee
11/21/2017 - 9:56 AM

element-ui@1.x 版动态隐藏表格固定列边样式的 directive

element-ui@1.x 版动态隐藏表格固定列边样式的 directive

const ElementTableCtx = '__ElementTableCtx';
function setShadowStyle(els, style) {
  for (const el of els) {
    el.style.boxShadow = style;
  }
}
export default function install(Vue) {
  Vue.directive('dynamic-fixed-column', {
    bind(el, binding) {
      function onScroll() {
        const { fixedEls, fixedRightEls, maxScrollWidth } = el[ElementTableCtx];
        let shadowStyle = null;
        if (this.scrollLeft === 0) {
          shadowStyle = 'none';
        } else {
          shadowStyle = null;
        }
        setShadowStyle(fixedEls, shadowStyle);

        if (this.scrollLeft === maxScrollWidth) {
          shadowStyle = 'none';
        } else {
          shadowStyle = null;
        }
        setShadowStyle(fixedRightEls, shadowStyle);
      }

      const bodyWrapper = el.querySelector('.el-table__body-wrapper');
      bodyWrapper.addEventListener('scroll', onScroll);

      el[ElementTableCtx] = {
        onScroll,
        expression: binding.expression,
        fixedEls: [],
        fixedRightEls: [],
        scrollEl: bodyWrapper,
        maxScrollWidth: 0,
        inited: false
      };
    },
    componentUpdated(el) {
      const { scrollEl } = el[ElementTableCtx];
      // if (inited) {return }
      const fixedEls = el.querySelectorAll('.el-table__fixed');
      const fixedRightEls = el.querySelectorAll('.el-table__fixed-right');
      if (fixedEls.length) {
        const maxScrollWidth = scrollEl.scrollWidth - scrollEl.clientWidth;

        el[ElementTableCtx].inited = true;
        el[ElementTableCtx].fixedEls = fixedEls;
        el[ElementTableCtx].fixedRightEls = fixedRightEls;
        el[ElementTableCtx].maxScrollWidth = maxScrollWidth;
        setShadowStyle(fixedEls, 'none');
      }
    },
    unbind(el) {
      const { scrollEl, onScroll } = el[ElementTableCtx];
      scrollEl.removeEventListener('scroll', onScroll);
    }
  });
}