vue+element-UI实现跟随滚动条加载表格数据

时间:2025-01-20 14:57:03

el-table当数据量大的时候,实现滚动到底部后加载数据,直接上js代码,有其他需求请各自更改

 第一步、在data中定义两个数组

  1. data() {
  2. return {
  3. innerList:[], //新数组,用于存放全部数据
  4. innerData:[], //el-table表格数组
  5. dom:null,
  6. }
  7. }

第二步、在数据发生改变的方法中先循环存放一部分数据用于页面显示

  1. watch: {
  2. data:{
  3. this.innerData=[];
  4. this.innerList=[];
  5. //将接口中获取到的数据全部存放到数组
  6. this.innerList = this.data.records || this.data.data || [];
  7. //先循环出100条数据用于显示
  8. for(let i=0;i<this.innerList.length;i++){
  9. if(i<100){
  10. this.innerData.push(this.innerList[i]);
  11. }
  12. }
  13. }
  14. }

第三步、在mounted监听滚动事件

  1. mounted() {
  2. // 设置滚动条监听时间加载数据
  3. this.dom = this.$refs.elTable.bodyWrapper;
  4. this.dom.addEventListener('scroll', () => {
  5. let scrollTop = this.dom.scrollTop; //滚动距离
  6. let scrollHeight = this.dom.scrollHeight; //滚动条的总高度
  7. let clientHeight = this.dom.clientHeight; //可视区的高度
  8. if (scrollTop + clientHeight === scrollHeight) {
  9. if (this.innerList.length <= this.innerData.length) return
  10. if (this.innerData.length + 50 > this.innerList.length) {
  11. // 如果不够50条就全部渲染上去
  12. this.dom.scrollTop = this.dom.scrollTop - 50;
  13. this.innerData=[];
  14. this.innerData.push(...this.innerList)
  15. } else {
  16. this.dom.scrollTop = this.dom.scrollTop - 50;
  17. let id = this.innerData.length;
  18. //每次渲染50条数据
  19. for (let index = id; index < id + 50; index++) {
  20. this.innerData.push(this.innerList[index])
  21. }
  22. }
  23. }
  24. })
  25. }