在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ù)遵倦,所以我們需要在頁(yè)面渲染之后重新 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: {
}
}