微信小程序實現滾動加載分頁處理 親測有效

你好,我是卍悟極!找了好多篇文章,有些看不懂的,有些看的似懂非懂的,很正常,別人寫的終究不如自己理解寫的,其實我們要的只是理解這個邏輯就可以了。

後端:是用的 thinkPHP5.1 框架(PHP)

我理解的原理:

1、初次加載數據爲第一頁的 onLoad:function(){} ;

2、每次拉到底部就相當於加載下一頁 onReachBottom: function () {} ;

3、當加載到最後一頁時,請給一個提醒 wx.showModel() ;

js(注意看註釋,別全照抄):

const app = getApp()
var page = 1  //初始化頁數
Page({
  data: {
    lists: [],
    lastpage:0,
  },
  // 生命週期函數--監聽頁面加載
  onLoad:function(){
    let that = this;
   //數據 初始化調用
    that.loadData(0); 
  },

  //數據加載
  loadData:function(page){
    let that = this;
    //顯示 加載中的提示
    wx.showLoading({
      title: '數據加載中...',
    })
    //獲取上次加載的數據
    var oldlists = this.data.lists;
    //獲取數據
    wx.request({
      url: 'https://localhoat/data', //接口地址 填你的數據接口
      method: "post",
      data: {'page': page},
      success: function (res) {
        console.log(res) //查看數據結構
        var newlists = oldlists.concat(res.data) //合併數據 res.data 你的數組數據
        setTimeout(() => {
          that.setData({
            lists: newlists,
            lastpage: res.data.last_page //你的總頁數
          });
        //隱藏 加載中的提示
          wx.hideLoading();
        }, 1500)
      },
    })
  },
  //加載更多
  onReachBottom: function () {
    page++
    if(this.data.lastpage > page){
      this.loadData(page); 
    }else{
      wx.showModal({
        title: '到底了',
        content: '請休息一會再看唄!',
      })
    }
  },
})

wxml(像這樣的UI的界面大家應該都可以隨手捏來得,數據結構根據自己請求的填,別跟着填{{item.title}}、{{item.content}這兩個:

<block wx:for="{{lists}}" wx:key="index" wx:for-item="item">
  <view class='lists' data-obj={{item}} data-index='{{index}}'>
     <view class='title'>{{item.title}}</view>
     <view class='content'>{{item.content}}</view>
  </view>
</block>

wxss 樣式自己隨便調調也可以了; 你好,我是卍悟極!

參考:

https://blog.csdn.net/u011072139/article/details/53940684

https://www.jianshu.com/p/c5046573682e

https://blog.csdn.net/qq_41408081/article/details/102600167

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章