Laravel+微信小程序实现上拉分页

所用的基本知识

Laravel分页

我一般是使用模型查询数据的,如果使用其它方法,详见官方文档

//以User为例
//无条件查询分页
$users = App\User::paginate(15);
//有条件查询分页
$users = App\User::where('id',1)->paginate(15);

微信小程序获取触底事件

主要的方法是onReachBottom,大前提是页面的scroll-view需要给一个固定值

总体思路

  • 首先需要完成后端接口的开发,将查询的数据传回前端
  • 微信小程序的页面在加载时,调用刚刚创建的那个接口
  • 当用户触发下拉触底事件时,调用第一步创建的那个接口,同时将page的值传给后端
  • 后端将数据传回小程序时,小程序将数据与原来的数据进行拼接,并显示出来
  • 如果后端传回的值为空,则显示没有更多的数据

具体实现

  1. Laravel分页
public function getUser(Request $request){
     return User::where('unit_id', $request->unit_id)
            ->where('parent_id', $request->id)
            ->paginate(10);
}
  1. wxml
<scroll-view style="height:{{height}};" bindscrolltolower="onReachBottom" bindscroll="scroll" class="test">
	<view class="cu-list menu-avatar">
  		<view wx:for="{{userList}}"  wx:key bindtouchstart="ListTouchStart">
    		<view class="name-list flex text-center" wx:if="{{item.isDelete==0}}">
      			<view class='name-width'>
        			<text>{{item.name}}</text>
      			</view>
      			<view class="userid-width">
        			<text>{{item.user_id}}</text>
      			</view>
      			<view class="unit-width">
        			<text>{{item.unit.unit_name}}</text>
      			</view>
      			<view class="title-width">
        			<text>{{item.title}}</text>
      			</view>
    		</view>
  		</view>
	</view>
</scroll-view>
  1. js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userList: {},
    page: 1,
    height: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res.windowHeight)
        that.setData({
          height: res.windowHeight
        })
      },
    })
    wx.request({
      url: app.globalData.Url + "/users",
      data: {
        unit_id: wx.getStorageSync('UserData').unit_id,
        id: wx.getStorageSync('UserData').id,
      },
      method: 'GET',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success(res) {
        that.setData({
          userList: res.data.data
        })
      }
    });
  },

  //分页
  onReachBottom: function (e) {
    var that = this;
    that.data.page += 1;
    var page = that.data.page;
    wx.request({
      url: app.globalData.Url + "/users?page=" + page,
      data: {
        unit_id: wx.getStorageSync('UserData').unit_id,
        id: wx.getStorageSync('UserData').id,
      },
      success(res) {
        console.log(res.data.data);
        that.setData({
          //向页面已有数据后面加数据
          //如果报错请查看两个数据的结构是否相同
          userList: that.data.userList.concat(res.data.data),
        })
        if (res.data.data == '') {
          wx.showToast({
            title: '没有更多数据',
          })
        }
      }
    })
  },

猜你喜欢

转载自blog.csdn.net/qq_42094066/article/details/96614637