微信小程序 解决swiper数量多导致渲染卡顿的解决方案

  在开发小程序时,我们经常会用到swiper组件实现轮播或者翻页效果,但是当swiper-item数量过多时,会造成视图层渲染卡顿的问题。

  有网友推荐的做法是只渲染三个swiper-item,分别是本条数据以及上一条和下一条,默认当前显示的swiper-item位置是中间那个,然后根据滑动动态更改三条数据,并把current位置设置回中间那个swiper-item,也就是current:1, 但是这种做法会在setData({current:1})时有个往回滑动的动画效果,这里也有个简单粗暴的解决办法就是通过设置duration='0'直接关闭动画,但不管怎样做,体验都是相对较差的。

   还有的网友的做法是先渲染n个空的swiper-item,n是当前数据的条数,然后只插入当前索引以及上下两条数据,并根据滑动动态修改对应位置的数据,这种做法比上一种更简单,优化了性能,也解决了翻页会有往回滑动动画的问题,但是当swiper-item量足够大时,比如1000条,渲染仍会非常卡顿。

个人认为最佳的解决办法是对第一种解决方案进行改进:

  1. 同样的是只在视图层渲染三个swiper-item,其它的数据存在数组中
  2. 在swiper组件中加入circular属性,使swiper可以衔接滑动
  3. 然后swiper中当前显示swiper-item的索引也是动态的,数据需要根据当前索引更新到对应位置,并不是直接将current固定在第二条,结合circular属性,就可以实现只渲染了三条swiper-item并且滑动无跳回,并解决了swiper数量过多导致渲染卡顿的问题。

现实的效果图:

gif效果图
gif效果图

直接说可能不太清晰,下面直接上代码

首先是wxml:

 ​
 <swiper circular bindchange="onSwiperChange">
 ​
   <swiper-item wx:for="{{displayList}}" wx:key="index">
 ​
     <view>{{item}}</view>
 ​
   </swiper-item>
 ​
 </swiper>
 ​

js:

 ​
 // 假设这是要渲染到swiper-item的数据
 ​
 let list = [1,2,3,4,5,6,7,8,9,10];
 ​
 // 这是当前swiper-item在list中的索引
 ​
 let index = 0;
 ​
 // 这是当前swiper-item在swiper中的索引
 ​
 let currentIndex = 0;
 ​
 Page({
 ​
   data: {
 ​
     // 要渲染到swiper-item的数组
 ​
     displayList:[],
 ​
   },
 ​
   onLoad() {
 ​
     this.upDateDisplayList();
 ​
   },
 ​
   // 更新当前displayList
 ​
   upDateDisplayList(){
 ​
     let displayList = [];
 ​
     displayList[currentIndex] = list[index];
 ​
     displayList[currentIndex-1 == -1 ? 2:currentIndex-1] = list[index-1 == -1 ? list.length-1 : index -1];
 ​
     displayList[currentIndex+1 == 3 ? 0:currentIndex+1]= list[index+1 == list.length ? 0 : index+1];
 ​
     this.setData({
 ​
       displayList,
 ​
     })
 ​
   },
 ​
   onSwiperChange(e){
 ​
     // 先判断是向前滑动还是向后滑动
 ​
     // current 为滑动后swiper-item的索引
 ​
     let current = e.detail.current
 ​
     // currentIndex是滑动前swiper-item的索引
 ​
     // 如果两者的差为2或者-1则是向后滑动
 ​
     if(currentIndex-current==2 || currentIndex-current==-1){
 ​
       index = index + 1 == list.length ? 0 : index + 1;
 ​
       currentIndex = currentIndex + 1 == 3 ? 0 : currentIndex + 1;
 ​
       this.upDateDisplayList();
 ​
     }
 ​
     // 如果两者的差为-2或者1则是向前滑动
 ​
     else if(currentIndex-current==-2 || currentIndex-current==1) {
 ​
       index = index - 1 == -1 ? list.length-1 : index - 1;
 ​
       currentIndex = currentIndex-1 == -1 ? 2 : currentIndex - 1;
 ​
       this.upDateDisplayList();
 ​
     }
 ​
   },
 ​
 })
 ​

 

如果大家有更好的解决方案,也欢迎一起讨论学习 !

 

  • 7
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值