1. 程式人生 > 實用技巧 >移動端H5頁面上拉載入更多功能實現(二)

移動端H5頁面上拉載入更多功能實現(二)

之前已經寫過一篇關於上拉載入更多的文章,那個主要是根據滾動實現分頁向後臺發起請求實現。這次實現方式為後臺返回所有需要載入的資料,前端這邊做視覺上的分頁效果。實現原理也是根據滾動距離觸發載入更多的條件。

我這邊的需求是需要在模態框裡實現一個列表的載入更多的功能。實現原理:根據彈框內的父元素的溢位高度也就是滾動高度超出十條資料的高度,立即觸發載入下一頁。

具體程式碼實現如下:

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 >= 800*pagecount) && 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,以此來保證陣列不再繼續累加(相當於阻止繼續請求的一個操作)。

以上。