小程序实现分页加载和下拉刷新很简单,因为它在Page中有相关的处理函数
onPullDownRefresh -- 监听用户下拉动作,实现下拉刷新
onReachBottom -- 页面上拉触底,实现分页加载
切记:想实现下拉刷新,必须在页面配置文件中(.json)添加 enablePullDownRefresh:true 开启下拉刷新
Page({
data:{
p:1, //分页请求
totalpage:null, //总页数
isloading:true, //是否显示加载动画
newsList:[] //数据
},
obtainNews:function(){
wx.showLoading({
title:'加载中...'
})
var that=this;
wx.request({
url:'url'+that.data.p,
data: {
token: that.data.token
},
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success:res=>{
if(res.data.status==500){ //没有更多数据
wx.showToast({
title:'没有数据了',
icon:'none'
})
that.setData({
isloading:true
})
}else{
var newsArr=that.data.newsList;
for(var i=0;i<res.data.info.length;i++){
newsArr.push(res.data.info[i])
}
that.setData({
newsList:newsArr,
isloading:true,
totalpage:res.data.totalpage
})
}
}
})
},
onPullDownRefresh:function(){
wx.showNavigationBarLoading(); //在当前页面显示导航条加载动画
this.onLoad(); //刷新页面
setTimeout(function(){
wx.hideNavigationBarLoading(); //在当前页面隐藏导航条加载动画
wx.stopPullDownRefresh(); //停止下拉动作
},2000)
},
onReachBottom:function(){
var p=this.data.p;
var totalpage=this.data.totalpage + 1;
p++;
if(p>totalpage){
return;
}
this.setData({
isloading: false,
p: p
})
this.obtainNews();
}
})