vue+swiper背景图随swiper改变

效果:div内部swiper滑动时,外部div背景图片随着变化
思路:获取swiper的索引,用:style定义背景图片
//template
//外部背景图片
<div class="cont-box" :style="{backgroundImage: 'url(' + bgImg[activeIndex].bg + ')'}">
  <div class="swiper-container" style="height: 100%; color: white;" ref="mySwiper" id="home">
        <div class="swiper-wrapper">
          <div  class="swiper-slide" v-for(item,index) in box-cont :key="index">

          </div>
       </div>
   </div>
</div>
//script
//引入swiper
import Swiper from 'swiper';
export default{
  data(){
    return{
      activeIndex:0,//索引默认是0
       bgImg:[{
          bg:require("../../static/images/bg_home.jpg")
         },{
          bg:require("../../static/images/bg_brand.jpg")
         },{
          bg:require("../../static/images/bg_news.jpg")
         },{
          bg:require("../../static/images/bg_video.jpg")
         },{
          bg:require("../../static/images/bg_product.jpg")
         },{
           bg:require("../../static/images/bg_joinin.jpg")
         },{
          bg:require("../../static/images/bg_contact.jpg")
         }],//背景图片
    }
  },
    mounted(){
    let that = this;
    //具体方法请查看swiper官方文档
    that.swiper = new Swiper('#home',{
        direction: 'vertical', // 垂直切换选项
        loop: false, // 循环模式选项
        pagination: '#swiper-pagination',
        paginationClickable: true,
        mousewheelControl : true,
        onSlideChangeStart: function(swiper){
          that.activeIndex = swiper.activeIndex //拿到当前的swiper索引
        }
      })
    }
}

这样就实现了,如果出现滚动有大约一秒的白屏情况,解决方法把图片提前缓存
此外可以添加动画效果来过渡
上一篇:swiper插件在移动端,多个swiper左右滑动时有空白的问题


下一篇:浅谈被Swiper的坑