Vue?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節(jié)點平級,聲明onReachBottom事件處理函數,用來監(jiān)聽頁面的上拉觸底行為:
// 觸底的事件
onReachBottom() {
// 讓頁碼值自增 +1
this.queryObj.pagenum += 1
// 重新獲取列表數據
this.getGoodsList()
}改造methods中的getGoodsList函數,當列表數據請求成功之后,進行新舊數據的拼接處理:
// 獲取商品列表數據的方法
async getGoodsList() {
// 發(fā)起請求
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
}優(yōu)化
通過節(jié)流閥防止發(fā)起額外的請求
在 data 中定義isloading節(jié)流閥如下:
data() {
return {
// 是否正在請求數據
isloading: false
}
}修改getGoodsList方法,在請求數據前后,分別打開和關閉節(jié)流閥:
// 獲取商品列表數據的方法
async getGoodsList() {
// ** 打開節(jié)流閥
this.isloading = true
// 發(fā)起請求
const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
// ** 關閉節(jié)流閥
this.isloading = false
// 省略其它代碼...
}在onReachBottom觸底事件處理函數中,根據節(jié)流閥的狀態(tài),來決定是否發(fā)起請求:
// 觸底的事件
onReachBottom() {
// 判斷是否正在請求其它數據,如果是,則不發(fā)起額外的請求
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('數據加載完畢!')
// 判斷是否正在請求其它數據,如果是,則不發(fā)起額外的請求
if (this.isloading) return
this.queryObj.pagenum += 1
this.getGoodsList()
}實現下拉刷新
在pages.json配置文件中,為當前的goods_list頁面單獨開啟下拉刷新效果:
"subPackages": [{
"root": "subpkg",
"pages": [{
"path": "goods_detail/goods_detail",
"style": {}
}, {
"path": "goods_list/goods_list",
"style": {
"onReachBottomDistance": 150,
"enablePullDownRefresh": true,
"backgroundColor": "#F8F8F8"
}
}, {
"path": "search/search",
"style": {}
}]
}]監(jiān)聽頁面的onPullDownRefresh事件處理函數:
// 下拉刷新的事件
onPullDownRefresh() {
// 1. 重置關鍵數據
this.queryObj.pagenum = 1
this.total = 0
this.isloading = false
this.goodsList = []
// 2. 重新發(fā)起請求
this.getGoodsList(() => uni.stopPullDownRefresh())
}修改getGoodsList函數,接收cb回調函數并按需進行調用:
// 獲取商品列表數據的方法
async getGoodsList(cb) {
this.isloading = true
const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
this.isloading = false
// 只要數據請求完畢,就立即按需調用 cb 回調函數
cb && cb()
if (res.meta.status !== 200) return uni.$showMsg()
this.goodsList = [...this.goodsList, ...res.message.goods]
this.total = res.message.total
}到此這篇關于Vue uni-app框架實現上拉加載下拉刷新功能的文章就介紹到這了,更多相關Vue uni-app內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

