您好,小程序模板欢迎您。
小程序模板
当前位置 : 首页> 小程序教程> 微信小程序解决swiper数量多导致渲染卡顿的解决方案

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

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


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

1、同样的是只在视图层渲染三个swiper-item,其它的数据存在数组中


2、在swiper组件中加入circular属性,使swiper可以衔接滑动


3、然后swiper中当前显示swiper-item的索引也是动态的,数据需要根据当前索引更新到对应位置,并不是直接将current固定在第二条,结合circular属性,就可以实现只渲染了三条swiper-item并且滑动无跳回,并解决了swiper数量过多导致渲染卡顿的问题。

wxml


  
    {{item}}
  


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();
    }
  },
})

联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了