VUE,ElementUI列表大数据操作卡顿问题?(已解决)

问题描述

前端UI框架使用的是ElementUI,项目要求数据不分页一个表格至少要1000条数据,这时点击其他DOM操作,会出现卡顿的现象。如点击复选框。

官网的示例也搞了,超过200行后操作就会卡很久,比如复选框

基于elementUI的table,在不修改源码的情况下支持大数据了渲染的场景

两种解决方案
一、Vue自定义指令 (通过自定义指令隐藏数据)
二、使用 pl table (轻松解决1w+数据量)

根据个人业务惊醒选择,我选择的是第二中解决方案

我们主要讲一下第一种解决方案,第二种可自行查看官网
话不多说直接贴代码

//指令代码

// 设置默认溢出显示数量
var spillDataNum = 20;

// 设置隐藏函数
var timeout = false;
let setRowDisableNone = function (topNum, showRowNum, binding) {
  if (timeout) {
    clearTimeout(timeout);
  }
  timeout = setTimeout(() => {
    binding.value.call(null, topNum, topNum + showRowNum + spillDataNum);
  });
};

export default {
  name: 'loadmore',
  componentUpdated: function (el, binding, vnode, oldVnode) {
    setTimeout(() => {
      const dataSize = vnode.data.attrs['data-size'];
      const oldDataSize = oldVnode.data.attrs['data-size'];
      if(dataSize === oldDataSize){
        return;
      }
      const selectWrap = el.querySelector('.el-table__body-wrapper');
      const selectTbody = selectWrap.querySelector('table tbody');
      const selectRow = selectWrap.querySelector('table tr');
      if (!selectRow) {
        return;
      }
      const rowHeight = selectRow.clientHeight;
      let showRowNum = Math.round(selectWrap.clientHeight / rowHeight);

      const createElementTR = document.createElement('tr');
      let createElementTRHeight = (dataSize - showRowNum - spillDataNum) * rowHeight;
      createElementTR.setAttribute('style', `height: ${createElementTRHeight}px;`);
      selectTbody.append(createElementTR);

      // 监听滚动后事件
      selectWrap.addEventListener('scroll', function () {
        let topPx = this.scrollTop - spillDataNum * rowHeight;
        let topNum = Math.round(topPx / rowHeight);
        let minTopNum = dataSize - spillDataNum - showRowNum;
        if (topNum > minTopNum) {
          topNum = minTopNum;
        }
        if (topNum < 0) {
          topNum = 0;
          topPx = 0;
        }
        selectTbody.setAttribute('style', `transform: translateY(${topPx}px)`);
        createElementTR.setAttribute('style', `height: ${createElementTRHeight-topPx > 0 ? createElementTRHeight-topPx : 0}px;`);
        setRowDisableNone(topNum, showRowNum, binding);
      })
    });
  }
};

关于全局引入指令代码
在main.js里面

import loadmore from '@/js/loadmore'
Vue.directive(loadmore.name,loadmore.componentUpdated);

思路
减少对DOM节点的渲染,通过滚动函数节流实现滚动后事件来动态渲染数据

Element Table代码






第一种方案参考了hally 大佬的 附上原文链接,侵删

个人更加推荐第二种方案就是pl-table

pl-table当前对应的element-ui的文档是 2.13.0, 更多配置具体请看element官方文档的table属性/事件/方法,因为有些属性/事件/方法很少用,所以没加入到plTable(完美解决万级数据渲染卡顿问题),过万数据点击全选卡顿,等等问题

重点: 流畅渲染万级数据并不会影响到 element-ui el-table组件的(原有)功能,并且新增了一些功能,具体请看属性配置

你可能感兴趣的:(VUE,ElementUI列表大数据操作卡顿问题?(已解决))