【小程序】分页加载数据,下拉加载更多,上拉刷新

版权声明:本文为博主原创文章,未经博主允许不得转载。原文链接http://blog.csdn.net/adayabetter?viewmode=contents https://blog.csdn.net/adayabetter/article/details/83112490

【 小程序】分页加载数据,下拉加载更多,上拉刷新

分页加载的优点就不多说了,下面主要记录一下几个问题点。

  1. scroll-view组件不能用在页面根布局中,不然触发不了系统的onPullDownRefresh()、onReachBottom()回调。
  2. 在Page页面配置中增加如下两项配置:
      enablePullDownRefresh: true,
      onReachBottomDistance: 100,
  1. 如何判断是否加载完毕?
      计算公式:
      (当前页数 - 1)* 每页加载个数 + 当前请求到的数据Data.length == 数据总数 ; // 则加载完毕 
  1. 详细代码参考

@1. data中定义变量

const LIMIT = 6 // 每次加载的个数
data{
      currentPage: 1,
      noMoreData: false,
      isLoading: false,
}

@2. 数据请求接口封装

/**
     *  获取热推产品信息
     */
    async getHotProductInfo(currentPage = 1, reset = false) {
      tips.loading()
      let params = {
        cityCode: 2500, // 默认上海
        page: currentPage,
        limit: LIMIT,
      }
      try {
        let result = await network.GET('https://##.com/dany/poster/##', params)
        tips.loaded()
        if (result && result.success && result.data && result.data.hotProduct && result.data.hotProductTotalCount) {
          // 判断是否加载完
          if ((currentPage - 1) * LIMIT + result.data.hotProduct.length === result.data.hotProductTotalCount) {
            this.noMoreData = true
          }
          let newHotProduct = JSON.parse(JSON.stringify(result.data.hotProduct))
          this.hotPushDatas.hotProduct = reset ?  newHotProduct : this.hotPushDatas.hotProduct.concat(newHotProduct)
          this.$apply()
        }
      } catch (e) {
        tips.loaded()
      }

    }

@3. 增加下拉、上拉回调方法

    async onPullDownRefresh() {
      await this.reload()
      wepy.stopPullDownRefresh()
    }
    onReachBottom() {
      if (this.noMoreData) {
        return
      }
      this.loadMore()
    }

    async loadMore() {
      if (this.noMoreData || this.isLoading) {
        return
      }
      this.isLoading = true
      this.currentPage += 1
      await this.getHotProductInfo(this.currentPage, false)
      this.isLoading = false
    }

    async reload() {
      this.noMoreData = false
      this.currentPage = 1
      return await this.getHotProductInfo(this.currentPage, true)
    }

@4. 在onLoad中执行,this.reload()初始化数据。

this.reload()

以上就是小程序下拉加载更多、上拉刷新当前数据的实现,有问题欢迎留言讨论。

猜你喜欢

转载自blog.csdn.net/adayabetter/article/details/83112490