微信小程序上拉加载onReachBottom
时间: 2024-01-05 10:11:38 浏览: 111
微信小程序中的onReachBottom事件可以用来实现上拉加载功能,当页面滚动到底部时,该事件会被触发。你可以在该事件中发送请求,获取更多的数据并渲染到页面上。
具体实现方法如下:
1. 在页面的json文件中,将onReachBottom事件声明为页面的事件之一:
```
{
"usingComponents": {},
"enablePullDownRefresh": true,
"navigationBarTitleText": "示例页面",
"onReachBottom": "onReachBottom"
}
```
2. 在页面的js文件中,编写onReachBottom事件的处理函数,该函数会在页面滚动到底部时被触发:
```
Page({
data: {
dataList: [], // 数据列表
pageNum: 1, // 当前页数
pageSize: 10, // 每页显示的数据条数
hasMoreData: true // 是否还有更多数据
},
// 上拉加载更多
onReachBottom: function () {
if (this.data.hasMoreData) {
this.loadData(this.data.pageNum + 1)
}
},
// 加载数据
loadData: function (pageNum) {
wx.showLoading({
title: '加载中'
})
wx.request({
url: 'https://xxx.com/api/data', // 请求接口地址
data: {
pageNum: pageNum,
pageSize: this.data.pageSize
},
success: res => {
wx.hideLoading()
if (res.data.code === 0) {
let dataList = this.data.dataList.concat(res.data.data)
this.setData({
dataList: dataList,
pageNum: pageNum,
hasMoreData: dataList.length < res.data.totalCount ? true : false
})
} else {
wx.showToast({
title: '加载失败',
icon: 'none'
})
}
},
fail: err => {
wx.hideLoading()
wx.showToast({
title: '加载失败',
icon: 'none'
})
}
})
}
})
```
在上述代码中,loadData函数用于获取数据并渲染到页面,同时更新页码和是否还有更多数据的状态。onReachBottom事件中调用loadData函数,传入当前页码加1的值,以获取下一页的数据。
另外,如果后端返回的数据中包含总数据量,我们可以通过比较当前列表的数据数量和总数据量来判断是否还有更多数据,从而控制是否继续加载。
阅读全文
相关推荐
















