实现原理:
- 下拉刷新:由于小程序数据是实时渲染的。我们把data{}内的数据清空重新加载即可实现下拉刷新。
- 上拉加载更多(页面上拉触底事件):新获取的数据追加到data{}内的原数据即可。由于小程序数据是实时渲染,小程序在保持原数据显示不变的基础上,自动追加渲染显示新数据。
注意(小程序官方有说明):
- 上拉加载更多 不要用scroll-view,用普通的view即可。
- 下拉刷新需要在 当前页面.json 里配置
{
"enablePullDownRefresh": true
}
- page()属性里有两个属性是关于页面下拉刷新 和 上拉加载更多的:
onPullDownRefresh Function 页面相关事件处理函数–监听用户下拉动作
onReachBottom Function 页面上拉触底事件的处理函数
文章列表页的demo代码:
index.wxml
<!--pages/home/index.wxml-->
<view class='container' wx:for="{{articles}}">
<!-- 文章列表 -->
<view bindtap="onArticle" data-aid="{{item.id}}">
<view class='a-title '>{{item.title}}</view>
<image class='a-thumb' src="{{item.thumb}}" mode="widthFix"></image>
</view>
</view>
index.js
**//pages/home/index.js
var page=0;//分页标识,第几次下拉,用户传给后台获取新的下拉数据
Page({
data: {
articles: [],//数组
},
// 页面加载
onLoad: function () {
this.clearCache();//清本页缓存
this.getArticles(0);//第一次加载数据
},
// 下拉刷新
onPullDownRefresh: function () {
this.clearCache();
this.getArticles(0);//第一次加载数据
},
// 页面上拉触底事件(上拉加载更多)
onReachBottom: function () {
this.getArticles(page);//后台获取新数据并追加渲染
},
// 清缓存
clearCache:function(){
page = 0;//分页标识归零
this.setData({
articles: [] //数组清空
});
},
// 点击跳转详情页
onArticle:function(){
//业务逻辑
},
/**
* 获取
* @param {int} pg 分页标识 默认0
*/
getArticles: function (pg) {
//设置默认值
pg = pg ? pg : 0;
var that = this;
var apiUrl = 'http://www.zhipur.com/Api/Article/getArticles';//地址
var postData = {
page: pg,//分页标识
app_version: 1.2,//当前版本,后台根据版本不同给出不同的数据格式
}
wx.request({
url: apiUrl,
data: postData,
method: 'POST',
header: { 'content-type': 'application/x-www-form-urlencoded' },
success: function (res) {
if (res.data.status == 1) {//成功
var tmpArr = that.data.articles;
// 这一步实现了上拉加载更多
tmpArr.push.apply(tmpArr,res.data.data);
that.setData({
articles: tmpArr
})
page++;
} else {//失败
console.log(res.data.info);
}
},
fail: function (e) {
console.log(e);
}
})
},
})**