微信小程序 onReachBottom 上拉加载
1、首先在data里定义一下返回数据data,和翻页的页数pagenum
data: {
pagenum: 1, //初始页默认值为0
loading: true,
endnotice:true
},
2、具体的请求过程,包含新老数据的数组合并,实现数据实时更新
getdatalist: function () { //可在onLoad中设置为进入页面默认加载
var that = this;
wx.request({
url: 'xxxxxxx/api/wxapp/productGetList',
data: {
"key": "aa",
"pageNum": that.data.pagenum, //从数据里获取当前页数
"pageSize": 6, //每页显示条数
},
success: function (res) {
// console.log(res.data.data.list);
if (res.data.code == 1){
var arr1 = that.data.datalist; //从data获取当前datalist数组
var arr2 = res.data.data.list; //从此次请求返回的数据中获取新数组
arr1 = arr1.concat(arr2); //合并数组
that.setData({
loading: true,
datalist: arr1 //合并后更新datalist
})
} else if(res.data.code == 0){
that.setData({
loading: true,
endnotice: false
})
}
},
fail: function (err) { },//请求失败
complete: function () { }//请求完成后执行的函数
})
},
3、翻页时更新页码pagenum+1,并触发新一轮请求,和第2部形成循环。
onReachBottom: function () { //触底开始下一页
var that = this;
var pagenum = that.data.pagenum + 1; //获取当前页数并+1
that.setData({
pagenum: pagenum, //更新当前页数
loading:false,
endnotice:true
})
that.getdatalist();//重新调用请求获取下一页数据
},
4、json 页面设置
{
"onReachBottomDistance": 2
}
5、php后端代码
$pageNum = max(1, $this->request->request('pageNum'));
$pageSize = $this->request->request('pageSize');
$pageindex=($pageNum-1) * $pageSize;
$list = Db::name('wxappproduct')->where('status', '=',1)->order('weigh desc,id')->limit($pageindex,$pageSize)->select();
if ($list) {
$this->success('返回成功', ['list' => $list]);
}else{
$this->error(__('no exists'));
}
6、wxml页面
<scroll-view scroll-y="true" class='product_body'> <template name="itmes"> <navigator url="../../pages/productshow/index?id={{list.id}}"> <image src='{{siteRoot}}{{list.smallimage}}' class="imagesty" mode="widthFix" lazy-load></image> <view class="protitle">{{list.name}}</view> </navigator> </template> </scroll-view> <!--循环输出列表 begin--> <view wx:for="{{datalist}}" wx:key="index" class="prolist"> <template is="itmes" data="{{list:item,siteRoot:siteRoot}}" /> </view> <!--循环输出列表 end--> <view class="loading" hidden="{{loading}}"> <van-loading size="24px" type="spinner">加载中...</van-loading> </view> <view class="endnotice" hidden="{{endnotice}}"> <van-divider contentPosition="center">数据已全部加载完毕</van-divider> </view>