携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第14天,点击查看活动详情
上次我们发布了我们的小程序,可喜可贺,审核通过了,大家可以小程序搜索宝宝账单,找到我们哦:
今天我们继续来完善我们的小程序,首先,我们新增了十几条数据,页面饱满起来了:
目前是一次性搜索所有记录,我们改改云函数,让接口每次只返回5条数据:
'use strict';
const db = uniCloud.database()
const _ = db.command
exports.main = async (event, context) => {
const collection = db.collection('bill')
const res = await collection.where({
'createTime': _.gt(event.beginTime),
'openid': event.openid
}).orderBy('createTime', 'desc')
.skip(event.limit * (event.pageNo - 1))
.limit(event.limit)
.get()
return res
};
我们根据时间倒序,每次查询5条数据:
getTotalFee() {
let month = new Date().getMonth() + 1;
month = month < 10 ? '0' + month : month;
let year = new Date().getFullYear();
let dateStr = `${year}-${month}-01 00:00:00`;
uni.showLoading({
title: '处理中...'
})
uniCloud.callFunction({
name: 'get',
data: {
beginTime: new Date(dateStr).getTime(),
openid: uni.getStorageSync('openid'),
+ limit: this.limit, // 5
+ pageNo: this.pageNo // 1
}
}).then((res) => {
uni.hideLoading()
this.feeList = res.result.data;
this.total = this.feeList.reduce((p, c) => Number(c.price) + p, 0);
})
},
我们发现本月总消费是不对的,我们应该在初始化页面的时候就调一次获取总的数据接口,点查看更多,获取分页查询
'use strict';
const db = uniCloud.database()
const _ = db.command
exports.main = async (event, context) => {
const collection = db.collection('bill')
const res = await collection.where({
'createTime': _.gt(event.beginTime),
'openid': event.openid
}).orderBy('createTime', 'desc')
+ .skip(event.limit ? event.limit * (event.pageNo - 1) : 0)
+ .limit(event.limit ? event.limit : 999999)
.get()
return res
};
getTotalFee() {
let month = new Date().getMonth() + 1;
month = month < 10 ? '0' + month : month;
let year = new Date().getFullYear();
let dateStr = `${year}-${month}-01 00:00:00`;
uni.showLoading({
title: '处理中...'
})
uniCloud.callFunction({
name: 'get',
data: {
beginTime: new Date(dateStr).getTime(),
openid: uni.getStorageSync('openid')
}
}).then((res) => {
uni.hideLoading();
this.totalTimes = res.result.affectedDocs;
this.total = res.result.data.reduce((p, c) => Number(c.price) + p, 0);
})
},
getList() {
let month = new Date().getMonth() + 1;
month = month < 10 ? '0' + month : month;
let year = new Date().getFullYear();
let dateStr = `${year}-${month}-01 00:00:00`;
uni.showLoading({
title: '处理中...'
})
uniCloud.callFunction({
name: 'get',
data: {
beginTime: new Date(dateStr).getTime(),
openid: uni.getStorageSync('openid'),
limit: this.limit,
pageNo: this.pageNo
}
}).then((res) => {
console.log(res);
uni.hideLoading();
this.feeList = this.feeList.concat(res.result.data);
})
},
区分获取总数据和分页数据。
点击查看更多:
viewMore() {
this.pageNo++;
this.getList();
}
这边有个小问题,就是没有限制当pageNo超过数据拥有的分页数时,返回的永远是空数组。我们限制一下:
viewMore() {
if (this.pageNo * this.limit >= this.totalTimes) {
uni.showToast({
title: '没有更多数据了',
icon: 'none'
})
return;
}
this.pageNo++;
this.getList();
}
分页查询就分享到这,觉得还不错的留下你的赞呀,或者扔收藏夹吃灰也不错啊。我们的小程序又推进了一步,加油,坚持就是胜利~睡觉