Vue使用swiper插件时特别是轮播元素含有动态数据时可能会出现数据为空或者白屏的问题
使用下面的方法可以解决(保证在数据请求之后再渲染页面)
- 页面结构
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide tpOne" v-if="topInfo">
<-- 此处为绑定数据的轮播元素 -->
<div class="bannerBox1">
<div class="l_label" >{{topInfo.label}}</div>
<div class="l_title" >{{topInfo.title}}</div>
<div class="l_tips" >{{topInfo.tips}}</div>
<div class="l_bottom"><span><img src="..." alt=""></span>{{topInfo.bottom}}</div>
</div>
</div>
<div class="swiper-slide"><img src="" alt="" /></div>
<div class="swiper-slide"><img src="" alt="" /></div>
<div class="swiper-slide"><img src="" alt="" /></div>
</div>
<div class="swiper-pagination"></div>
</div>
- 初始化方法
//mounted 或者topInfo的值获取到时再调用初始化方法
swiperInit() {
var mySwiper = new Swiper('.swiper-container', {
pagination : '.swiper-pagination',
paginationType : 'bullets',
autoplay : 2000,
// loop : true,
})
},
- 获取数据
getInfo:function(){
var _this=this;
XXX.ajax({
url: '...',
success: (r)=> {
if(!!r.ret){
_this.topInfo=r.ret;
//此时获取到数据再显示Swiper
_this.getFlag=1;
}
}
})
},
下面再提供一个例子
- 页面结构
<div class="swBox" v-if="sw_flag&&!!banners.length">
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(banner,index) in banners" :key="index" @click="toNextUrl(banner,index)">
<img :src="banner.image" alt="" />
</div>
</div>
<div class="swiper-pagination"></div>
</div>
</div>
- 初始化方法
swiperInit() {
var mySwiper = new Swiper('.swiper-container', {
pagination : '.swiper-pagination',
paginationType : 'bullets',
autoplay : 2000,
observer:true,
observeParents:false
})
},
- 获取数据
getData:function(){
var _this=this;
//此处设置sw_flag变量的目的在于控制swiper显示关闭开关,当数据重新请求时,先关闭swiper,请求完毕数据再重新渲染页面;
_this.sw_flag=0;
XXX.ajax({
url: '...',
success: (r)=> {
if(!!r.ret){
_this.banners=r.ret.banners||"";
_this.sw_flag=1;
//此时获取到数据再初始化swiper
_this.$nextTick(function(){
if(!!_this.banners.length){
_this.swiperInit();
}
});
}
}
})
},
注:我用的swiper版本是 3.4.2