這篇文章主要講解了“uni-app如何實現數據上拉加載更多功能”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“uni-app如何實現數據上拉加載更多功能”吧!
打開項目根目錄中的 pages.json 配置文件,為 subPackages 分包中的商品 goods_list 頁面配置上拉觸底的距離:
"subPackages": [ { "root": "subpkg", "pages": [ { "path": "goods_detail/goods_detail", "style": {} }, { "path": "goods_list/goods_list", "style": { "onReachBottomDistance": 150 } }, { "path": "search/search", "style": {} } ] } ]
在 goods_list 頁面中,和 methods 節點平級,聲明 onReachBottom 事件處理函數,用來監聽頁面的上拉觸底行為:
// 觸底的事件 onReachBottom() { // 讓頁碼值自增 +1 this.queryObj.pagenum += 1 // 重新獲取列表數據 this.getGoodsList() }
改造 methods 中的 getGoodsList 函數,當列表數據請求成功之后,進行新舊數據的拼接處理:
// 獲取商品列表數據的方法 async getGoodsList() { // 發起請求 const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj) if (res.meta.status !== 200) return uni.$showMsg() // 為數據賦值:通過展開運算符的形式,進行新舊數據的拼接 this.goodsList = [...this.goodsList, ...res.message.goods] this.total = res.message.total }
在 data 中定義 isloading 節流閥如下:
data() { return { // 是否正在請求數據 isloading: false } }
修改 getGoodsList 方法,在請求數據前后,分別打開和關閉節流閥:
// 獲取商品列表數據的方法 async getGoodsList() { // ** 打開節流閥 this.isloading = true // 發起請求 const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj) // ** 關閉節流閥 this.isloading = false // 省略其它代碼... }
在 onReachBottom 觸底事件處理函數中,根據節流閥的狀態,來決定是否發起請求:
// 觸底的事件 onReachBottom() { // 判斷是否正在請求其它數據,如果是,則不發起額外的請求 if (this.isloading) return this.queryObj.pagenum += 1 this.getGoodsList() }
如果下面的公式成立,則證明沒有下一頁數據了:
當前的頁碼值 * 每頁顯示多少條數據 >= 總數條數
pagenum * pagesize >= total
修改 onReachBottom 事件處理函數如下:
// 觸底的事件 onReachBottom() { // 判斷是否還有下一頁數據 if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('數據加載完畢!') // 判斷是否正在請求其它數據,如果是,則不發起額外的請求 if (this.isloading) return this.queryObj.pagenum += 1 this.getGoodsList() }
感謝各位的閱讀,以上就是“uni-app如何實現數據上拉加載更多功能”的內容了,經過本文的學習后,相信大家對uni-app如何實現數據上拉加載更多功能這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。