在數據量較大時采用后端分頁是常用的方法,與PC端不同的是,移動端分頁往往不借助分頁條,而是向上滑動觸發對下一頁的請求。在小程序里,向上滑動會觸發onReachBottom事件,在該事件里發起對下一頁的請求即可。
首先在列表底部添加一個提示表現當前列表狀態
<div class="loading-text"> ----{{loadingType === 0 ? contentText.contentdown : (loadingType === 1 ? contentText.contentrefresh : contentText.contentnomore)}}---- </div>
// 默認值為 0 contentType: 0, contentText: { contentdown: "上拉顯示更多", contentrefresh: "正在加載...", contentnomore: "沒有更多數據了" }
contentText 有三種狀態,
loadingType = 0 —— “上拉顯示更多”
loadingType = 1 —— “正在加載...”
loadingType = 2 —— “沒有更多數據了”
樣式:
.loading-text { margin-top: 15rpx; text-align: center; font-size: 26rpx; color: #999; }
准備工作就緒!
首先在 onLoad 階段請求列表數據
apiGetListData(this.page, this.rows).then(res => { let list = res.value.list; // 返回的數據等於請求的最大條數,表示下一頁可能還有數據 if (list.length == this.rows) { this.loadingType = 0; } else { // 返回的數據小於請求的最大條數,表示下一頁沒有數據了 this.loadingType = 2; } this.list = list; })
其中 apiGetListData 是封裝好的 Pormise 請求,需要的參數為當前頁碼(默認值是 1)以及每頁數據條數(這里要注意設置的數據條數一定要能觸底,不然永遠觸發不了onReachBottom事件)。
接着當用戶滑動列表,就要重新發起請求,page + 1,rows 不變,請求到的數據跟原始數據拼接。這時我們會發現與上面的請求有很多重復操作,因此可以改寫一下封裝個新方法。
getListData() { apiGetListData(this.page, this.rows).then(res => { let list = res.value.list; // 返回的數據等於請求的最大條數,表示下一頁可能還有數據 if (list.length == this.rows) { this.loadingType = 0; } else { // 返回的數據小於請求的最大條數,表示下一頁沒有數據了 this.loadingType = 2; } // 如果沒有數據返回說明已經返回完了,記錄狀態,不用拼接 if(!coupons.length) { this.hasNoMoreData = true; return; } // 跟原始數據拼接 this.list = this.list.concat(list); }) }
onReachBottom() { // 如果沒有數據了不再繼續請求 if (this.hasNoMoreData) return; this.page++ // 顯示“正在加載...” this.loadingType = 1; this.getListData(); },
至此,就完成了一個簡單的小程序分頁功能。