微信小程序上拉加载,分页数据

目录

1.页面上拉加载

2.scroll-view上拉加载


1.页面上拉加载

微信小程序提供onReachBottom()上拉事件,链接:https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html#onReachBottom

onReachBottom()事件直接调用就可以。

在进行调用时要对当前页和总页数进行对比,判断是否要进行刷新数据

data: {
    list:'',//数据列表
    page:1,//请求的第几页
    size:10,  //每页多少条哦  
    totalpage:1,//总页数
  }, 
onShow() {
    this.getList()
  },
// 上拉事件
  onReachBottom(){
    if(this.data.page<=this.data.totalpage){
      this.getList()
    }
  },
 getList(){
    let page=this.data.page
     //接口参数
    let params={
      page: this.data.page,
      size: this.data.size
    }

    //获取数据的接口请求成功后
        page++
        this.setData({
          [`list[${this.data.page-1}]`]:items,//items:后台返回数据
          page:page,
          totalpage:res.data.totalpage
        })
        //... [`list[${this.data.page-1}]`]:items这种写法是为避免setData数据量过大,list数据在使用时需注意多循环一层

  },
<block class="" wx:for="{
   
   {list}}" wx:for-item="pitem" wx:for-index="pindex" wx:key="{
   
   {pindex}}">
   <view class="" wx:for="{
   
   {pitem}}" wx:key="{
   
   {index}}">{
   
   {item}}</view>
</block>

2.scroll-view上拉加载

请先看文档https://developers.weixin.qq.com/miniprogram/dev/component/scroll-view.html

在这里需要用到lower-threshold, bindscrolltolower两个属性

lower-threshold:距底部/右边多远时,触发 scrolltolower 事件,默认值50

bindscrolltolower:滚动到底部/右边时触发

其实也没什么好说的,和页面上拉加载是一样的

注意:bindscrolltolower 到底部会一直触发,需要要定义一个变量来控制

.wxml

<scroll-view scroll-y="true" style="height: 100%;" lower-threshold="200" bindscrolltolower="scrollToLower">
</scroll-view>

.js

data: {
    list:'',//数据列表
    page:1,//请求的第几页
    size:10,  //每页多少条哦  
    totalpage:1,//总页数
    loading:false,//控制变量
  }, 
onShow() {
    this.getList()
  },
// scroll-view触底事件
  scrollToLower(){
    if(!this.data.loading && this.data.page<=this.data.totalpage){
      this.setData({
        loading:true
      })
      this.getList()
    }
  },
 getList(){
    let page=this.data.page
     //接口参数
    let params={
      page: this.data.page,
      size: this.data.size
    }

    //获取数据的接口请求成功后
        page++
        this.setData({
          [`list[${this.data.page-1}]`]:items,//items:后台返回数据
          page:page,
          totalpage:res.data.totalpage,
          loading:false
        })

  },

猜你喜欢

转载自blog.csdn.net/kxmzl/article/details/128083155