作者: 老葛 亚艾元软件
在前面的代码里面,我们成功的将小程序和Drupal结合了起来。但是我们的这个列表,还有所不足,只去了前面10条数据。如果用户想看后面的数据怎么办,这就涉及到了一个分页的问题。不过在手机上面,我们不准备实现一个和Drupal类似的分页器功能,实现的要具有小程序(手机端)特色。这就是手机屏幕滚动到最下面的时候,自动加载下10条记录。Drupal端,我们需要提供分页的支持,我们选用的是完整分页。一页10条记录。
在微信小程序端,我们将代码做以下修改:
Page({
data: {
title: '',
page: 0,
pageSize: 10,
hasMoreData: true,
type:'',
items: []
},
getArticles: function (message) {
var that = this;
wx.request({
url: 'http://chess.yaiyuan.com/jsonnews/' + that.data.type + '?page=' + that.data.page,
method: 'GET',
success:function(res) {
var nodelist = res.data
var itemsTem = that.data.items
if (nodelist.length < that.data.pageSize) {
that.setData({
hasMoreData: false,
items: itemsTem.concat(nodelist)
})
}else{
that.setData({
hasMoreData: true,
page: that.data.page + 1,
items: itemsTem.concat(nodelist)
})
}
//console.log(that.data.items)
}
})
},
onReachBottom: function() {
// Do something when page reach bottom.
//this.getArticles();
if (this.data.hasMoreData) {
this.getArticles('加载更多数据')
} else {
wx.showToast({
title: '没有更多数据',
})
}
},
onLoad: function (options) {
console.log('onLoad')
var that = this;
var type = options.type;
var title = "";
if(type == 1){
title = '象棋动态';
}
if(type == 2){
title = '象棋赛事';
}
if(type == 3){
title = '象棋典故';
}
that.setData({
title: title,
type:type
})
that.getArticles();
}
})
在这里,在页面的data里面,我们增加了:
page: 0,
pageSize: 10,
hasMoreData: true,
这三个参数是用来做分页的,page用来标识当前的页码;pageSize表示一次多少条;hasMoreData,布尔值,用来标识当前还有没有更多数据。
我们将获取数据的任务封装成为了一个getArticles函数,里面包含了向Drupal端发起http请求。里面的代码我们已经熟悉了。我们这里做了对应修改,主要是处理分页的逻辑。
var itemsTem = that.data.items
if (nodelist.length < that.data.pageSize) {
that.setData({
hasMoreData: false,
items: itemsTem.concat(nodelist)
})
}else{
that.setData({
hasMoreData: true,
page: that.data.page + 1,
items: itemsTem.concat(nodelist)
})
}
如果当前返回的数据的条数,小于pageSize,表示后面没有更多数据了。否则的话,表示还有更多数据。
微信小程序提供了接口:onReachBottom ,我们通过实现这个接口,
onReachBottom: function() {
// Do something when page reach bottom.
//this.getArticles();
if (this.data.hasMoreData) {
this.getArticles('加载更多数据')
} else {
wx.showToast({
title: '没有更多数据',
})
}
},
这样在到达底部的时候,如果还有更多数据,我们继续加载;如果没有更多数据了,我们提示一下用户,信息提供的对话框,使用wx.showToast。
在onload接口里面,我们初始化一下数据,然后调用getArticles。