真香系列:vue table 滚动加载数据指令

530 阅读1分钟

注册全局指令

// main.js 里面
import tableScroll from './directive/tableScroll';
Vue.use(tableScroll);

用法

  <el-table v-table-scroll="handleSetTableData">

源码

function scrollTable(dom, scrollTop, binding) {
  const isBottom = dom.scrollHeight - dom.scrollTop === dom.clientHeight;
  const isHorizontal = scrollTop === dom.scrollTop;
  if (isBottom && !isHorizontal && dom.scrollTop !== 0) {
    if (binding.value) {
      binding.value(); // 函数执行
    }
  }
  if (!isHorizontal) {
    scrollTop = dom.scrollTop;
  }
}
const tableScroll = {
  bind: function(el, binding, vnode, oldVnode) {
    const scrollTop = 0;
    const dom = el.querySelector('.el-table__body-wrapper');
    el.tempScroll = scrollTable;
    el.tempDom = dom;
    el.tempFnc = ()=>{
      el.tempScroll(dom, scrollTop, binding);
    };
    dom.addEventListener('scroll', el.tempFnc);
  },
  unbind(el) {
    el.tempDom.removeEventListener('scroll', el.tempFnc);
    el.tempScroll = null;
    el.tempFnc = null;
  }
};

const install = function(Vue) {
  Vue.directive('tableScroll', tableScroll);
};

if (window.Vue) {
  window.permit = tableScroll;
  Vue.use(install); // eslint-disable-line
}
tableScroll.install = install;
export default tableScroll;