日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

uni-app 數據上拉加載更多功能

作者:船長在船上 更新時間: 2022-04-04 編程語言

實現上拉加載更多

  • 打開項目根目錄中的 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() }
		
	

原文鏈接:https://blog.csdn.net/SmartJunTao/article/details/123684356

欄目分類
最近更新