现在是一次性加载所有的记录数据,数据多的时候,会加载比较慢,所以我们改成分页加载,一次最多加载15条数据
每次拉倒底部都会自动加载下一页的数据,知道所有的数据加载完成
编辑record.vue文件,添加两个变量page和more
page默认为0,表示当前的页数;more默认为true,用来控制底部显示的信息
data () {
return {
show_record:false,
userinfo:{},
records:[],
page: 0,
more: true
}
},
<p class="text-footer" v-if="!more">
没有更多数据
p>
<p class="text-footer" v-else-if="records.length < 15">
p>
<p class="text-footer" v-else>
加载中···
p>
根据下面的提示编辑方法
async getRecords () {
//调用后台数据时显示「加载中」提示框
wx.showToast({
title: '加载中',
icon: 'loading'
})
//***需要添加的代码***
if(this.page === 0){
this.records = []
}
//需要传到后台的数据
const data = {
openid: this.userinfo.openId,
//***需要添加的代码***
page: this.page
}
//将后台传过来的数据保存到records变量中
const records = await get('/weapp/getrecords', data)
//concat是拼接数组的方法,将新查出的数据,拼接到records数组中
//***需要编辑的代码***
// this.records = records.records
this.records = this.records.concat(records.records)
//***需要添加的代码***
//每次在数据库中查找15条数据,如果查出的数据不足15条说明这是最后一页了,将more改为false
if (records.records.length < 15 && this.page > 0) {
this.more = false
}
//通过records数组的长度来判断show_record变量为false或者true
if(this.records.length === 0){
this.show_record = true
}else{
this.show_record = false
}
console.log("从后台返回的记录数据:",this.records)
wx.hideToast()
}
onReachBottom函数是到达小程序页面底部会触发的函数,我们在这里面调用getRecords方法,每次小程序页面下拉到底部,都会自动触发getRecords方法,调用record数据
//参考代码,无需粘贴
//onShareAppMessage(e) {
//...
//},
// 需要添加的代码
onReachBottom () {
// 如果more为false,说明没有更多数据了,不需要再加载getRecords方法,return结束加载
if (!this.more) {
return false
}
// 加载下一页
this.page = this.page + 1
console.log("this.page",this.page)
this.getRecords()
},
也就是server/controllers/getrecords.js文件,接收到当前的页面page数据,加载相应数据
//原代码
const {openid} = ctx.request.query
//修改为
const {openid,page} = ctx.request.query
//原代码
const records = await mysql('records')
.select('id','add','mark','note','create_time')
.where("openid",openid)
.orderBy('id','desc')
//修改为
const records = await mysql('records')
.select('id','add','mark','note','create_time')
.where("openid",openid)
.orderBy('id','desc')
.limit(15).offset(Number(page) * 15)
limit n offset m
是mysql的分页语句
代码从m行开始查,查找n条数据
每次切换到记录页面,用户应该最想看到最新数据,所以需要将page变量设为0
//getRecords方法添加一个参数init
async getRecords (init) {
if(init){
this.page = 0
this.more = true
}
//参考代码,无需粘贴
//wx.showToast({
//title: '加载中',
//icon: 'loading'
//})
//...
//}
//原代码
this.getRecords()
//修改为
this.getRecords(true)
下拉函数我们之前讲过是onPullDownRefresh,使用这个函数,需要现在main.json文件里面授权
{
"enablePullDownRefresh":true
}
//参考代码,无需粘贴
//onReachBottom () {
//…
//}
//需要添加的代码
onPullDownRefresh () {
this.getRecords(true)
wx.stopPullDownRefresh()
}
保存所有修改的文件,打开微信开发者工具测试效果
在首页点击按钮,生成20条左右的记录
切换到记录页面,查看下面几个方面:
作者:猫宁一
全栈程序媛₍ᐢ •⌄• ᐢ₎一枚~ 热爱学习!热爱编程!
可关注【猫宁一】公众号领取我所有全栈项目代码哦~点击查看课程目录:微信小程序全栈开发课程目录