使用场景
js 使用Swiper实现轮播效果,swiper依赖动态数据改变(使用vue.js来更新数据的),比如轮播图数量的变化,轮播图的显隐的变化。
参考网站
https://my.oschina.net/jamesview/blog/2988530
代码
<div class="swiper-container" v-if="isLoading==1">
<div class="swiper-pagination"></div>
<div class="swiper-wrapper">
<div class="swiper-slide">
<div style="margin-top:10px">
<div style=" width: 360px;font-size: 20px;font-family:PingFang-SC-Bold;">swiper-slide1</div>
</div>
</div>
<div class="swiper-slide">
<div style="margin-top:10px">
<div style="font-size: 20px;font-family:PingFang-SC-Bold;">swiper-slide2</div>
</div>
</div>
<div class="swiper-slide">
<div style="margin-top:10px">
<div style="font-size: 20px;font-family:PingFang-SC-Bold;">swiper-slide3</div>
</div>
</div>
</div>
</div>
基本用法基本官网上都可以找得到,可以看到我的代码中swiper在isLoading为true时才进行显示,则初始化需要放在数据更新以后,即isLoading变化为1以后,
我是用的vue.js 此方法放在Vue实例的methods中:
//数据更新后执行此方法
swiperInit() {
console.log("swiperInit");
this.isLoading = 1
this.$nextTick(function () {
console.log("after init swiper")
var mySwiper = new Swiper('.swiper-container', {
paginationClickable: true,
pagination: {
el: '.swiper-pagination'
},
on: {
touchStart: function (event) {
console.log('touchstart;', mySwiper.activeIndex);
},
touchMove: function (event) {
console.log('touchmove', mySwiper.activeIndex);
},
touchEnd: function (event) {
console.log('touchend', mySwiper.activeIndex);
}
}
})
})
}
注意
初始化一定要放在this.$nextTick之后,如果动态数据更新后立刻执行new Swiper的话,会出现无法轮播,总页数为0等情况。
分析的原因
Vue更新DOM为异步更新,数据变化后,DOM不会立刻更新,而是等同一事件循环中的所有数据变化完成之后再统一进行视图更新,此时立刻进行swiper初始化,会按照DOM变化前进行初始化。
nextTick是在同一事件循环中的数据变化后,DOM完成更新,立即执行nextTick(callback)内的回调,这个时候再进行swiper初始化,即可达到想要的效果。