1. 程式人生 > 實用技巧 >小程式分頁,滾動條滾到底部時往列表裡新增資料

小程式分頁,滾動條滾到底部時往列表裡新增資料

最近做小程式分頁,可以有兩種處理方式,一種是滾動到底部顯示下一頁,另一種是滾動到底部,往列表里加一頁資料,我用的是第二種,效果比第一種好多了

wxml:列表底部新增文字提示:

<view wx:if="{{goodsList.length > 0}}" class="loading"> {{loadingTxt}}</view>

wxss:

  1. .loading{
  2. text-align: center;
  3. font-size: 12px;
  4. margin: 10px 0;}

  js 引數定義:

Page({

  /**
   * 頁面的初始資料
   */
  data: {
    /**分頁引數 */
    keyword: '',
    searchStatus: false,
    goodsList: [],
    page: 1,
    size: 2,
    id: 0,
    loadingTxt: '',
    noMoreData: false,
  },

資料請求方法:

//獲取列表
  getGoodsList: function (paged = false) {
    let that = this;
    // util.request(api.GoodsList, { id: that.data.selectedId, page: that.data.page, size: that.data.size }, 'POST').then(function (res) {

      util.request(app.globalData.api_site + app.globalData.api_goods_list, 'GET',
        {
          category_id: '0',
          keywords: '',//搜素
          page_size: that.data.size,
          page_index: that.data.page,
          wid: app.globalData.subDomain,
          fromplat: app.globalData.fromplat
        }
      ).then((res) => {

        if (res.status === 1) {
        let goods = [];
        if (!paged) {
          goods = res.data;
          console.log('goods',goods);
      
        } else {
          //當滾動到頁面底部時,往列表裡新增資料,其它情況(關鍵字查詢,頁籤切換等)只顯示一頁資料
          goods = that.data.goodsList.concat(res.data);//concat:複製整個陣列到前面的陣列
        }
        that.setData({
          loadingTip: '',
          noMoreData: false,
          goodsList: goods,
        });
        if (res.data.length < that.data.size) {
          that.setData({
            loadingTxt: '沒有更多內容',
            noMoreData: true,
          });
        }
      }
    });
  },

其他地方呼叫

/**
* 頁面相關事件處理函式--監聽使用者下拉動作
*/
  onPullDownRefresh: function () {
this.data.page = 1
this.getGoodsList();
},

/**
* 頁面上拉觸底事件的處理函式
*/
onReachBottom: function () {
if (!this.data.noMoreData) {
this.data.page = this.data.page + 1;
this.getGoodsList(true);
};
},

頁面顯示:index.wxml

    <view class="goods-box" wx:for-items="{{goodsList}}" wx:key="{{index}}" bindtap="toDetailsTap" data-id="{{item.id}}">
           <view class="img-box">
              <image src="{{item.focusImgUrl}}" class="image" mode="aspectFill" lazy-load="true"/>
           </view>
           <view class="goods-title">{{item.productName}}</view>
           <view style='display:flex;'>
            <view class="goods-price">¥ {{item.salePrice}}</view>
            <view wx:if="{{item.marketPrice && item.marketPrice > 0}}" class="goods-price" style='color:#aaa;text-decoration:line-through'>¥ {{item.marketPrice}}</view>
           </view>           
        </view>

完成 結束。

轉載於:https://www.cnblogs.com/flysem/p/9358240.html