当前位置:   article > 正文

uni-app 数据上拉加载更多功能_uniapp上拉加载更多

uniapp上拉加载更多

实现上拉加载更多

在页面中,和 methods 节点平级,声明 onReachBottom 事件处理函数,用来监听页面的上拉触底行为

// 触底的事件
onReachBottom() {
  // 让页码值自增 +1
  this.pageNum += 1
  // 重新获取列表数据
  this.getPageList()
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

改造 methods 中的 getPageList 函数,当列表数据请求成功之后,进行新旧数据的拼接处理:

// 获取商品列表数据的方法
async getPageList() {
  // 发起请求
  const { data: res } = await uni.$http.get('https://*******', {.....})
  if (res.status !== 200) return uni.$showMsg()
  // 为数据赋值:通过展开运算符的形式,进行新旧数据的拼接
  this.pageList = [...this.pageList, ...res.data.list]
  this.total = res.data.total
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

优化:

通过节流阀防止发起额外的请求

data() {
  return {
    // 是否正在请求数据
    isloading: false,
    total: 0,
    pageList: [],
    pageNum:1,
    pageSize: 8
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

修改 getPageList 方法,在请求数据前后,分别打开和关闭节流阀:

// 获取商品列表数据的方法
async getPageList() {
  // ** 打开节流阀
  this.isloading = true
  // 发起请求
  const { data: res } = await uni.$http.get('https://*******', {.....})
  // ** 关闭节流阀
  this.isloading = false
 
  // 省略其它代码...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在 onReachBottom 触底事件处理函数中,根据节流阀的状态,来决定是否发起请求:

// 触底的事件
onReachBottom() {
  // 判断是否正在请求其它数据,如果是,则不发起额外的请求
  if (this.isloading) return
  this..pageNum += 1
  this.getPageList()
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

判断数据是否加载完毕
当前的页码值 * 每页显示多少条数据 >= 总数条数
pageNum * pageSize >= total

// 修改 onReachBottom 事件处理函数


// 触底的事件
onReachBottom() {
  // 判断是否还有下一页数据
  if (this.pageNum * this.query.pageSize >= this.total) return uni.$showMsg('数据加载完毕!')
 
  // 判断是否正在请求其它数据,如果是,则不发起额外的请求
  if (this.isloading) return
 
  this.pageNum += 1
  this.getPageList()
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/221363?site
推荐阅读
相关标签
  

闽ICP备14008679号