微信小程序上拉加载与下拉刷新
文章目录
上拉加载
应用场景:
微信内容页上拉加载,拉到最底部出现提示文案
思路:
1.初始页号为1
2.使用微信自带的方法onReachBottom检测滚动到底部,页号pageNo+1,然后去请求后台接口,把最新返回的结果添加到原来的数组里,重新渲染思路有了那么我们开始上代码把
3.当你调取的接口里的数据length<pageSize
Page({
data: {
page: 1,
pages: 0,
articles: []
},
onLoad(options) {
// 页面初次加载,请求第一页数据
this.getInfoListData(1)
},
onReachBottom() {
// 下拉触底,先判断是否有请求正在进行中
// 以及检查当前请求页数是不是小于数据总页数,如符合条件,则发送请求
if (!this.loading && this.data.page < this.data.pages) {
this.getInfoListData(this.data.page + 1)
}
},
getInfoListData(pageNo) {
this.loading = true
// 向后端请求指定页码的数据
return getArticles(pageNo).then(res => {
const articles = res.items
this.setData({
page: pageNo, //当前的页号
pages: res.pages, //总页数
articles: this.data.articles.concat(articles)
})
}).catch(err => {
console.log( err)
}).then(() => {
this.loading = false
})
}
})下拉刷新
1.配置json
{
"enablePullDownRefresh": true
}2.
Page({
data: {
page: 1,
pages: 0,
articles: []
},
onLoad(options) {
// 页面初次加载,请求第一页数据
this.getInfoListData(1, true)
},
onReachBottom() {
// 下拉触底,先判断是否有请求正在进行中
// 以及检查当前请求页数是不是小于数据总页数,如符合条件,则发送请求
if (!this.loading && this.data.page < this.data.pages) {
this.getInfoListData(this.data.page + 1)
}
},
onPullDownRefresh() {
// 上拉刷新
if (!this.loading) {
this. getInfoListData(1, true).then(() => {
// 处理完成后,终止下拉刷新
wx.stopPullDownRefresh()
})
}
},
getInfoListData(pageNo, over) {
this.loading = true
// 向后端请求指定页码的数据
return getArticles(pageNo).then(res => {
const articles = res.items
this.setData({
page: pageNo, //当前的页号
pages: res.pages, //总页数
articles: over ? articles : this.data.articles.concat(articles)
})
}).catch(err => {
console.log( err)
}).then(() => {
this.loading = false
})
}
})备注:
如果你需要局部的相应功能,你可以尝试使用<scroll-view>做容器,并通过它的bindscrolltoupper和bindscrolltolower来监听内容到顶或到底的事件,模拟实现出上拉加载和下拉刷新功能。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论