一、loop循环失效:

vue中使用v-for循环加载swiper的组件时

<div class='swiper__content'>
       <swiper :options="swiperOption" ref="mySwiper" class="swiper__content-item">
           <swiper-slide class="swiper-list" v-for="(item, index) in headerNotice" :key='index'>
               <div class="item-wrapper">
                   {{ item.content }}
               </div>
           </swiper-slide>
       </swiper>
   </div>

data数据为:

data() {
        return {
            swiperOption: {
                direction: 'vertical',
                autoplay: {
                    delay: 4000,
                    disableOnInteraction: false
                },
                loop: true
            },
            headerNotice: [
                {
                    content: 1,
                },{
                    content: 2,
                },{
                    content: 3,
                }
            ]
        };
    },

即使是设置了loop:true 还是不能无缝轮播
原因: loop设置为true 则开启loop模式。loop模式:会在原本slide前后复制若干个slide(默认一个)并在合适的时候切换,让Swiper看起来是循环的, 可是在vue的v-for中时,异步加载的数据都还没有返回时,就先加载了Swiper组件并复制了sliper

解决办法: 利用v-if的属性,v-if=showProduct.length,确保异步加载的数据已经返回后,再加载swiper组件

<div class='swiper__content' v-if='headerNotice && headerNotice.length > 0'>
            <swiper :options="swiperOption" ref="mySwiper" class="swiper__content-item">
                <swiper-slide class="swiper-list" v-for="(item, index) in headerNotice" :key='index'>
                    <div class="item-wrapper">
                        {{ item.content }}
                    </div>
                </swiper-slide>
            </swiper>
        </div>

还有一种办法就是直接设置定时器然后调用切换到下一个

var mySwiper = new Swiper('.swiper-container');
setInterval(function() {
	mySwiper.slideNext();
}, 1000)

二、当路由跳转回来后轮播失效,需要手动滑动一下才自动轮播的问题解决:
如果vue使用了缓存,当路由跳转回来时候swiper的自动轮播会失效,可以尝试重新渲染页面,使用v-if来实现.
template中:

<div v-if='reRender'>
<div class='swiper__content' v-if='headerNotice && headerNotice.length > 0'>
     <swiper :options="swiperOption" ref="mySwiper" class="swiper__content-item">
           <swiper-slide class="swiper-list" v-for="(item, index) in headerNotice" :key='index'>
               <div class="item-wrapper">
                   {{ item.content }}
               </div>
           </swiper-slide>
       </swiper>
   </div>
</div>

script中的activated中:

data() {
        return {
            swiperOption: {
                direction: 'vertical',
                autoplay: {
                    delay: 4000,
                    disableOnInteraction: false
                },
                loop: true
            },
            headerNotice: [
                {
                    content: 1,
                },{
                    content: 2,
                },{
                    content: 3,
                }
            ],
            reRender: false
        };
    },
activated() {
        this.reRender = false;
        setTimeout(() => {
            this.reRender = true;
        }, 100);
    }
Logo

前往低代码交流专区

更多推荐