微信小程序实现滚动加载分页处理 亲测有效

你好,我是卍悟极!找了好多篇文章,有些看不懂的,有些看的似懂非懂的,很正常,别人写的终究不如自己理解写的,其实我们要的只是理解这个逻辑就可以了。

后端:是用的 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

发布了52 篇原创文章 · 获赞 15 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41408081/article/details/102465765
今日推荐