1. 程式人生 > >【小程式】分頁載入資料,下拉載入更多,上拉重新整理

【小程式】分頁載入資料,下拉載入更多,上拉重新整理

【 小程式】分頁載入資料,下拉載入更多,上拉重新整理

分頁載入的優點就不多說了,下面主要記錄一下幾個問題點。

  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()

以上就是小程式下拉載入更多、上拉重新整理當前資料的實現,有問題歡迎留言討論。