在vue組件中使用swiper,而swiper中的數(shù)據(jù)是ajax獲取的,會(huì)導(dǎo)致輪播沒有效果。
這是因?yàn)閍jax獲取數(shù)據(jù)是異步的,所以new swiper()會(huì)先執(zhí)行,等到ajax數(shù)據(jù)獲取之后,dom重新渲染,但是此時(shí)swiper早就初始化完成了,輪播圖里并不會(huì)有ajax請(qǐng)求回的新數(shù)據(jù),所以我們需要在頁面渲染之后重新 new swiper()。
解決方法:使用 vue.nextTick() 和 setTimeout()
export default {
data(){
return{
}
},
created() {
},
mounted() {
this.$nextTick(()=>{
setTimeout(()=> {
this.mySwiper = new Swiper('.swiper-container', {
slidesPerView: 3,
spaceBetween: 30,
centeredSlides: true,
loop: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
autoplayDisableOnInteraction: false,
observer: true, //修改swiper自己或子元素時(shí),自動(dòng)初始化swiper
observeParents: true //修改swiper的父元素時(shí),自動(dòng)初始化swiper
})
},300)
})
},
methods: {
}
}