uniapp实现上拉加载,下拉刷新

1.上拉加载

打开项目根目录中的 pages.json 配置文件,为 subPackages 分包中的 goods_list 页面配置上拉触底的距离,在对应path下添加    "onReachBottomDistance": 触发触底函数的距离

      "path": "goods_list/goods_list",
      "style": {
        "onReachBottomDistance": 150,
        "backgroundColor": "#F8F8F8"
      }

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

    // 触底的事件
    onReachBottom() {
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕!')

      if (this.isloading) return

      // 让页码值自增+1
      this.queryObj.pagenum++
      this.getGoodsList()
    },

2.下拉刷新 

onPullDownRefresh

在 js 中定义 onPullDownRefresh 处理函数(和onLoad等生命周期函数同级),监听该页面用户下拉刷新事件。

  • 需要在 pages.json 里,找到的当前页面的pages节点,并在 style 选项中开启 enablePullDownRefresh
  • 当处理完数据刷新后,uni.stopPullDownRefresh 可以停止当前页面的下拉刷新。

再在刚才的style节点下添加如下代码,允许下拉刷新

        "enablePullDownRefresh": true,

同样的位置添加onPullDownRefresh处理函数

// 下拉刷新的事件
onPullDownRefresh() {
  // 1. 重置关键数据
  this.queryObj.pagenum = 1
  this.total = 0
  this.isloading = false
  this.goodsList = []

  // 2. 重新发起请求
  this.getGoodsList(() => uni.stopPullDownRefresh())
}

修改 getGoodsList 函数,接收 cb 回调函数并按需进行调用:

// 获取商品列表数据的方法
async getGoodsList(cb) {
  this.isloading = true
  const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
  this.isloading = false
  // 只要数据请求完毕,就立即按需调用 cb 回调函数
  cb && cb()

  if (res.meta.status !== 200) return uni.$showMsg()
  this.goodsList = [...this.goodsList, ...res.message.goods]
  this.total = res.message.total
}

对于onPullDownRefresh和onReachBottom两个函数不太理解的可以参考以下资料:

uni-app生命周期详解_linux小百的博客-CSDN博客

onPullDownRefresh | uni-app官网

猜你喜欢

转载自blog.csdn.net/m0_63748493/article/details/126897848