建议一
请求数据后再初始化swiper实例
理由
一开始我是按照GitHub上的文档配置swiper的:
<template>
<swiper :options="swiperOption">
<swiper-slide v-for="slide in swiperSlides">I'm Slide {{ slide }}</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
export default {
name: 'carrousel',
data() {
return {
swiperOption: {
pagination: {
el: '.swiper-pagination'
}
},
swiperSlides: [1, 2, 3, 4, 5]
}
},
mounted() {
setInterval(() => {
console.log('simulate async data')
if (this.swiperSlides.length < 10) {
this.swiperSlides.push(this.swiperSlides.length + 1)
}
}, 3000)
}
}
</script>
然后在mounted中请求自己的数据,把请求到的数据放到swiperSlides中,结果发现轮播的时候出现错误,轮播到最后一个时再往后轮播就会回到第二个,不会回到第一个。
这个时候就比较头疼了,找了很久都找不到原因,最后想到一个方法就是先请求到数据再初始化swiper这个实例,最后就可以了。
附上代码:
method: {
async getList() {
const _self = this;
try {
const res = await getList();
const { list } = res.data.page;
this.carouselList = list;
this.$nextTick(() => {
this.swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
autoplay: 5000,
autoplayDisableOnInteraction: false,
onlyExternal: false,
initialSlide: 0,
loop: true,
onSlideChangeStart(swiper) {
console.log(swiper.realIndex);
_self.currentIndex = swiper.realIndex;
}
});
if (this.isAutoChange) {
this.swiper.startAutoplay();
} else {
this.swiper.stopAutoplay();
}
});
} catch (err) {
console.log(err);
}
},
}
大功告成!
建议二
再次请求数据前最好先停止自动轮播
理由
如果需要一段时间更新轮播数据,则最好是先停止当前轮播再发送请求
附上代码:
mounted() {
this.getList();
this.dataTimer = setInterval(() => {
this.swiper.stopAutoplay();
this.getList();
}, 60000);
},