微信小程序实现上拉加载更多注意事项

223 阅读1分钟

微信小程序中如果我们想实现一个上拉加载更多的效果其实还是比较容易的,但上拉触底中出现的一些问题你真的注意到了么!!!

html

<template>
  <view class="goodsListBox">
    <view class="goods-list">
      <view  v-for="(goods, i) in goodsList" :key="i">
        <!-- 组件 -->
        <goods :goods="goods"></goods>
      </view>
      
    </view>
  </view>
</template>

js

export default {
    data() {
      return {
        goodsList:[],
        pagenum: 1, //页码
        pagesize: 10, //每页显示几条数据
        total:0,
      };
    },
    onLoad(){
      this.getList()
    },
    methods:{
      async getList(){
        const {data:res}=await uni.$http.get('/api/public/v1/goods/search')
        console.log(res)
        this.goodsList=res.message.goods
        this.total=res.message.total
      }
    }
  }
</script>

这是一段很简单的列表渲染的代码,效果如下:

39c9bcbbba17f484c3899dec9f48d38.png

以上只是简单的实现了一个列表的渲染,页面到底我们继续上拉是不能实现加载更多的

接下来开始实现上拉加载更多的效果:

1.首先我们需要修改触底距离:(根据需要,可改可不改,默认值为50)

打开项目根目录中的 pages.json 配置文件,为 list 页面配置上拉触底的距离:

image.png

实现上拉触底需要触发微信小程序中的一个生命周期函数 onReachBottom()

image.png

onReachBottom(){//上拉触底
        //页码值+1
        this.pagenum+=1;
       
        //重新加载数据
         this.getList()
}

image.png

现在再看效果:

20220614_093133.gif

现在已经实现了一个下拉加载更多的效果

但你以为这样就结束了么??? 重点在后面~~~~~~~

为了效果更明显,我们把小程序模拟器的网速调慢 先看效果:

20220614_095148.gif

在数据加载过程中,如果用户反复上下滑动鼠标,我们会发现还会发请求,那么如何才能组织这些额外的请求呢?

接下来我们要实现 通过节流阀防止发起额外的请求

在 data 中定义 isloading 节流阀如下:

data() {
  return {
    // 是否正在请求数据
    isloading: false
  }
}

async getList(){
        //打开节流阀
        this.loading=true
        const {data:res}=await uni.$http.get('/api/public/v1/goods/search')
        //关闭节流阀
        this.loading=false
        ....其他代码
      },

在onReachBottom函数中

 onReachBottom(){//上拉触底
      //判断是否属于加载中,如果加载中就不做任何操作,如果加载完毕才实现其他操作
       if(this.loading) return 
        //页码值+1
        this.pagenum+=1;
        this.getList()
        //重新加载数据
      }

这个我们就实现了节流的处理

问题2: 当数据加载完毕,我们继续滚动鼠标时,我们会发现还是会发起请求,所以,我们还需要判断数据是否加载完毕

 onReachBottom(){//上拉触底
      //判断是否记载完毕、
      if(this.pagesize * this.pagenum>=this.total) retuen;
      //判断是否属于加载中,如果加载中就不做任何操作,如果加载完毕才实现其他操作
       if(this.loading) return 
      
        //页码值+1
        this.pagenum+=1;
        this.getList()
        //重新加载数据
      }

这样才实现了完整的上拉记载更多~~~~