vue中触底加载

78 阅读1分钟
 <div v-if="loading" style="width: 100%;text-align: center;padding: 20px 0px;">加载中...</div>
data() {
    return {
      allData: [], // 所有数据
      chunkSize: 10, // 每次加载的数量
      loading: false, // 加载状态
      currentPage: 1 ,// 当前页数
    };
  },
mounted() {
   
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      const scrollHeight = document.documentElement.scrollHeight;
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const clientHeight = document.documentElement.clientHeight;
      // 当滚动条距离底部不足 100px 时,认为触底
      if (scrollHeight - (scrollTop + clientHeight) < 100) {
        // 执行触底操作
        // this.loadMoreData();
        if(this.list.length >= this.allData.length ){

        }else if(this.list.length < this.allData.length && !this.loading){
            this.loading = true;
            setTimeout(() => {
              const startIndex = (this.currentPage - 1) * this.chunkSize;
              const endIndex = startIndex + this.chunkSize;
              this.list = [...this.list, ...this.allData.slice(startIndex, endIndex)];
              this.currentPage++;
              this.loading = false;
            },1000)
            
        }
            
      }
    },
  }
  数据
   if(res.data.poolApplicationList && res.data.poolApplicationList.length > 0){
          // this.list = res.data.poolApplicationList
          // this.list = []
          // const use2DArrItem = (page) => {
          //       // 4. 从第一项,取到最后一项
          //       if (page > res.data.poolApplicationList.length - 1) {
          //           // console.log("每一项都获取完了");
          //           return;
          //       }
          //       requestAnimationFrame(() => {
          //           this.list =  this.list.concat(res.data.poolApplicationList[page])
          //           page = page + 1;
          //           use2DArrItem(page);
          //       });
          //   };
          //   use2DArrItem(0);
            this.issunfa = false
            this.list = []
            this.currentPage = 1
            this.loading = true;
            this.allData = res.data.poolApplicationList
            const startIndex = (this.currentPage - 1) * this.chunkSize;
            const endIndex = startIndex + this.chunkSize;
            this.list = [...this.list, ...this.allData.slice(startIndex, endIndex)];
            this.currentPage++;
            this.loading = false;
        }else{
          this.allData = []
          this.list = []
          this.issunfa = true
        }
        
     注释的为动画帧函数