加载数据的方法loadMore(),逻辑如下图:
源码如下:
data: {
category: {},//分类
shops: [],//列表
pageIndex: 0,//当前页码
pageSize: 20,//每页条数
totalCount: 0,//总条数
hasMore: true,//是否加载更多
searchShowed: false,
searchText: ''//查询文字
},
loadMore() {
// 有数据,加载
if (this.data.hasMore){
// 构造查询条件
let pageIndex = this.data.pageIndex
let pageSize = this.data.pageSize
let searchText = this.data.searchText
let params = {
_page: ++pageIndex,
_limit: pageSize
}
// 判断是否有查询条件
if (searchText) params.q = searchText
return fetch(`/categories/${this.data.category.id}/shops`, params)
.then(res => {
var totalCount = parseInt(res.header['X-Total-Count'])
// 一开始就设置为true,后面根据逻辑重置这个数据
var hasMore = true
if (totalCount <= this.data.pageSize) {//第一页
hasMore = false
} else {//非第一页:<时true,如:40<80;=时false,如:80<80
hasMore = params._page * this.data.pageSize < totalCount
}
const shops = this.data.shops.concat(res.data)//追加前几页的数据
// 把改变的数据均同步到页面中
this.setData({
shops,
totalCount,
pageIndex,
hasMore
})
})
}else{
return
}
},