微信小程序:scroll-view组件滑动多次触发scroll事件的bug解决

在项目开发过程中,组件是微信小程序提供给我们的一个分页器,一般滑动到底部时会触发scroll事件,scroll事件中往往包含对后端数据的请求;若是还未滑动到底部时频繁触发事件,则会频繁发请求,达不到想到的分页效果。
先来说说的用法

<scroll-view scroll-y="true" style="height:{containerHeight}px" lower-threshold="300" on-scrolltolower={this.getList()}>
</scroll-view>

在data中设置两个变量:

data: {
containerHeight: 0,
doneLoading: false
}

在页面加载时调用两个函数:

onLoad: function(option) {
  this.setContainerHeight();
 this.getList();
}

函数的具体实现:

setContainerHeight(){
    const systemInfo = wx.getSystemInfoSync();
    this.data.containerHeight = systemInfo.windowHeight - 50;
},
getList() {    
    /*这里是data中的原始分页信息数据*/
    const data = this.data;
    const that = this;
    const pageInfo = data.pageInfo;
    /*下面是对设置的开关的处理*/
    if (data.doneLoading) {
        return;
    }
    data.doneLoading = true;
    /*发异步请求(根据具体项目中对http请求的封装)*/
    if(data.pageInfo.totalCount>data.cancelList.length){
      CancelInfo.getCanceltList({
        currentPage: data.pageInfo.currentPage
      }).then(res => {
        if (res.retCode === 200) {
            data.pageInfo.currentPage = res.data.paginationInfo.currentPage + 1;
            data.pageInfo.totalCount = res.data.paginationInfo.totalRecord;
            data.cancelList = data.cancelList.concat(res.data.dataInfo);
        }
        /*请求成功重设开关*/
        data.doneLoading = false;
      }).catch(err => {
            console.log(err);
        })
    }
  },

解决办法:
设置一个开关变量,也就是这里的doneLoading
当开关为true时,getList整个函数从头执行到尾,包括发请求;当开关为false时,会执行判断语句中的”return;”这样处理可以将控制权返回给页面,后面的异步发请求以及处理请求数据的过程会留到下次scroll事件符合触发条件时再触发;这样可以有效的减少请求频繁触发。
使用还必须注意设置滚动的方向滚动器的高度;一般来说可以通过调用微信小程序的wx.getSystemInfoSync()接口,获取系统信息中的可使用的窗口高度,根据页面的展示情况,得到的可使用高度;当然,也可以直接给固定值,具体看开发需求。

猜你喜欢

转载自blog.csdn.net/qq_35585701/article/details/81162239