场景一 使用swiper时候需要loop轮播,但是如果数据较少的时候swiper会重复渲染数据, 我这里是切换形式,前面两个数量多可以loop但是第三个数据比较少就产生这个问题了

其实我的数据只有2条,但是却给我渲染了6条 

我第一想法想通过v-if,设置两个组变量渲染,结果fail

<swiper class="Swiper" :options="swiperOption" ref="mySwiper" v-if="currentBrandName != 'xxx'">
              <swiper-slide class="nuberItem"
                @click.native="jumpSale"
                v-for="(item, index) in data.saleList"
                :key="index"
                @mousemove.native="swiperMove"
                @mouseout.native="swiperOut">
               {{ item.carName }}:{{ $utils.qff(item.number) }}辆
              </swiper-slide>
            </swiper>

            <swiper class="Swiper" :options="swiperOption1" ref="mySwiper" v-else >
              <swiper-slide class="nuberItem"
                @click.native="jumpSale"
                v-for="(item, index) in data.saleList"
                :key="index"
                @mousemove.native="swiperMove"
                @mouseout.native="swiperOut">
               {{ item.carName }}:{{ $utils.qff(item.number) }}辆
              </swiper-slide>
            </swiper>

swiperOption: {
        observer: true,
        observeParents: true,
        slidesPerView: 'auto',
        // slidesOffsetBefore : 20,
        // spaceBetween: 8,
        // resistanceRatio: 0 ,
        freeMode: true,
        centeredSlides: false,
        centerInsufficientSlides: false,
        autoplay: {
          delay: 800,
          disableOnInteraction: false
        },
        speed: 1000,
        loop: true
      },
      swiperOption1: {
        observer: true,
        observeParents: true,
        slidesPerView: 'auto',
        // slidesOffsetBefore : 20,
        // spaceBetween: 8,
        // resistanceRatio: 0 ,
        freeMode: true,
        centeredSlides: false,
        centerInsufficientSlides: false,
        autoplay: {
          delay: 800,
          disableOnInteraction: false
        },
        speed: 1000,
        loop: false
      },

这会很dom里面保留了之前轮播的数据

 看了一下官网文档原因应该就是这个玩意

 这个参数并没有什么用

第二步在这两个swiper上分别绑定一个key值然后就解决了

<swiper class="Swiper" :options="swiperOption" ref="mySwiper" v-if="currentBrandName != 'xx'" :key="currentBrandName">


<swiper class="Swiper" :options="swiperOption1" ref="mySwiper" v-else :key="currentBrandName">

至此dom结构数据正常了。 

总结  v-if  + 绑定唯一key, 目的是为了重新渲染dom结构,同时把swiper的缓存去掉,数量较少的时候就不让数据轮播就ok了

Logo

一站式 AI 云服务平台

更多推荐