小程序实现滚动列表懒加载

609 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情

前言

除了小程序端,在移动端,大家应该都遇到过这种情况,请求接口返回的数据太多条,数据加载后一下子都渲染到页面上,会导致页面卡顿,一般遇到滚动页面懒加载的情况,大家都会监听页面滚动距离,scrollTop+screenHeight等于滚动高度scrollHeight如果scrollHeight和设备信息里的窗口高度一直,则说明滚动到了底部,触发事件。

微信原生组件scroll-view

微信的原生组件scroll-view里就已经有属性bindscrolltoupper/bindscrolltolower来实现刷新和滚动列表懒加载事件了

image.png

第一步,在wxml文件里引入scroll-view组件

  <scroll-view scroll-y="true" bindscrolltoupper="upper" bindscrolltolower="lower">
          <block wx:for="{{list}}" wx:key="index"></block>
  </scroll-view>

第二步,在js文件里定义请求事件

 Page(){
     data:{
         count:5   //初次请求5条数据
     },
     onLoad(){},
     upper(){
         this.GetInfo(5) //刷新请求默认5条
     },
     lower(){
          this.data.count  += 5  //每次滑动到底部再请求5条数据
          this.GetInfo(this.data.count)
     },
     GetInfo(num){
         wx.request({
             url:url,
             data:{
                 count:num
             },
             method:'GET',
             success:res=>{
                 if(res.statusCode == 200)  this.setData({ list : res.data })
             }
         })
     }
 }

未完待续续...