之前已经写过一篇关于上拉加载更多的文章,那个主要是根据滚动实现分页向后台发起请求实现。这次实现方式为后台返回所有需要加载的数据,前端这边做视觉上的分页效果。实现原理也是根据滚动距离触发加载更多的条件。
我这边的需求是需要在模态框里实现一个列表的加载更多的功能。实现原理:根据弹框内的父元素的溢出高度也就是滚动高度超出十条数据的高度,立即触发加载下一页。
具体代码实现如下:
getOffsetHeight(){this.$nextTick(() => { //使用nextTick为了保证dom元素都已经渲染完毕
let cardList =[];
let pagecount= 0;
let receivedcardList= this.receivedState[this.isStateActive].cardList;for(let i = 0; i<= receivedcardList.length ; i+=10){
cardList.push(receivedcardList.slice(i,i+10))
}this.receivedState[this.isStateActive].cardList =cardList[pagecount];this.$refs.receivedCardList.onscroll = ()=>{if(this.isLoading){if((this.$refs.receivedCardList.scrollTop >= (730 + pagecount*730)) && this.isStateActive == 1){
if(pagecount >=cardList.length){this.isLoading = false;
}else{this.isLoading = true;
pagecount++;if(cardList[pagecount] && cardList[pagecount].length> 0){this.receivedState[this.isStateActive].cardList = this.receivedState[this.isStateActive].cardList.concat(cardList[pagecount]);
}
}
}
}
}
})
}
其中: receivedcardList 接收到的是后台返回的所有数据的一个数组,定义一个cardList 将receivedcardList分割成十条一组的数据组成的数组,然后对cardlist 进行操作。通过监听ref获取的dom元素的滚动高度 来做条件判断。定义一个分页变量,每次加载超过分页乘以定义好的滚动距离 即可触发条件。当分页大小超过cardList长度值就将变量isLoading 设置为false,以此来保证数组不再继续累加(相当于阻止继续请求的一个操作)。
以上。