微信小程序上拉加载

下面是一个示例,在个人使用的过程中按自己需求进行更改

创建一个DataController控制器

php artisan make:controller DataController

创建一个Data的模型,并且在datas表里面创建两个字段,以name和description为例

php artisan make:model Data

下面是Datacontroller控制器里面的接口示例代码

<?php

namespace App\Http\Controllers;

use App\Models\Data;
use Illuminate\Http\Request;

class DataController extends Controller
{
    //
    public function getData(Request $request)
    {
        $page = $request->query('page', 1);
        $perPage = $request->query('perPage', 10);

        $data = Data::paginate($perPage, ['*'], 'page', $page);

        return response()->json($data);
    }
}

下面是Data模型里面的代码

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Data extends Model
{
    public $table='datas';
    protected $fillable = [
        'name',
        'description',
        // 其他字段...
    ];
}

给该接口一个路由

//微信小程序上拉加载
Route::get('data',[\App\Http\Controllers\DataController::class,'getData']);

接下来是微信小程序的代码,我给它加了一些样式,可以自行 更改

微信小程序的wxml代码

<view class="data-list">
  <block wx:for="{{ dataList }}" wx:key="index">
    <view class="data-item">
      <view class="data-item-name">{{ item.name }}</view>
      <view class="data-item-description">{{ item.description }}</view>
    </view>
  </block>
</view>

微信小程序的js代码

Page({
  data: {
    dataList: [], // 存储接口返回的数据
    currentPage: 1, // 当前页码
    perPage: 10, // 每页显示的数据数量
    isLoading: false, // 是否正在加载数据
    hasMore: true // 是否还有更多数据
  },
  
  onLoad: function() {
    this.getDataList();
  },
  
  // 请求接口数据
  getDataList: function() {
    if (this.data.isLoading || !this.data.hasMore) {
      return;
    }
    
    this.setData({
      isLoading: true
    });
    
    wx.request({
    //下面的url需要更换成自己的接口 url:
'http://www.day.com/index.php/data', data: { page: this.data.currentPage, perPage: this.data.perPage }, success: res => { const newDataList = res.data.data; const totalPage = res.data.last_page; const currentPage = res.data.current_page; this.setData({ dataList: this.data.dataList.concat(newDataList), currentPage: currentPage + 1, isLoading: false, hasMore: currentPage < totalPage }); }, fail: error => { console.error('Failed to fetch data:', error); this.setData({ isLoading: false }); } }); }, // 上拉加载更多 onReachBottom: function() { this.getDataList(); } });

下面是json的代码

{
  "onReachBottomDistance": 50,
  "usingComponents": {}
}

接下来是wxss代码

/* pages/page/page.wxss */


.data-list {
  padding: 20rpx;
}

.data-item {
  margin-bottom: 20rpx;
  background-color: #f2f2f2;
  padding: 10rpx;
  border-radius: 5rpx;
}

.data-item-name {
  font-size: 16px;
  font-weight: bold;
}

.data-item-description {
  margin-top: 5rpx;
  color: #666;
}

在数据库里面datas表里面生成一些数据

 这时候,就可以在微信开发者工具里面实现上拉加载的效果,下面是效果图

 

 

 注意,以上是示例代码,在个人开发中按照自己的需求对其更改

posted @ 2023-07-10 10:23  还好阿卡  阅读(179)  评论(0编辑  收藏  举报