上拉加载
uniapp中的上拉加载是通过onReachBottom()这个生命周期函数实现,当下拉触底时就会触发。当请求分页数据时,则通过这个函数进行加载。此时可以利用全局变量pageIndex首次赋值为1来进行参数的传递,当下拉加载下一页时,则让this.pageIndex++。
//部分代码
data(){
return {
pageIndex:1,
list:[]
}
},
methods:{
getList(){
uni.request({
url:"/api/getGoods?pageindex="+this.pageIndex
},succcess:res=>{
this.list=res.data.message
})
}
}
复制代码
但此时有一个问题:当获取下一页数据时,之前的数据消失,所以,应该将之前数据保留,所以使用扩展运算符,将数据展开放到数组里。成功后的函数应该写为:this.list=[...this.list,...res.data.message]
此外,还有一个问题,当下拉刷新时需要判断下一页还有没有数据,不能一直刷新请求。若后台返回总条数total,则用总数对10取余,若不为0,则return。若后台没有返回总条数,则需要使用this.list.length来判断,判断函数可写为:if(this.list.length<this.pageIndex*10) return
上拉刷新
在page.json中开启刷新(enablePullDownRefresh:true),监听下拉刷新函数为onPullDownRefresh(),当触发下拉刷新时
//将this.pageIndex = 1,初始化
onPullDownRefresh(){
this.pageIndex = 1
this.list=[]
//优化体验,延迟刷新,当刷新完毕后关掉刷新
setTimeOut(()=>{
this.getList(()=>{
uni.stopPullDownRefresh()
})
},1000)
}
//通过callback接收回调函数
getList(callback){
uni.request({
url:"/api/getGoods?pageindex="+this.pageIndex
},succcess:res=>{
this.list=[...this.list,...res.data.message]
callBack&&callBack()
})
}
复制代码