解决swiper4在vue项目中loop循环轮播失效

在vue(2.5.x)中使用swiper(4.3.3),轮播加了autoplay和loop、observer、observeParents等参数还是很诡异的无法循环轮播;

那么可以这样写代码试试:

<template>
  <div class="swiper-container banner">
        <div class="swiper-wrapper">
            <div v-for='(item, i) in banner_list' :key='i' class="swiper-slide">
                <router-link :to="{ path: '/details', query: {id: item.id}}">
                  <img :src='item.picUrl' alt="图片加载失败">
                </router-link>
            </div>
        </div>
        <!-- 如果需要分页器 -->
        <div class="swiper-pagination"></div>

        <!-- 如果需要导航按钮 -->
        <!-- <div class="swiper-button-prev"></div>
        <div class="swiper-button-next"></div> -->

        <!-- 如果需要滚动条 -->
        <!-- <div class="swiper-scrollbar"></div> -->
    </div>
</template>

<script>
import Swiper from 'swiper'
export default {
  data () {
    return {
      banner_list: []
    }
  },
  methods: {
    initSwiper () {
      this.swiper = new Swiper('.banner', {
        loopAdditionalSlides: 3,
        loop: true,
        autoplay: {// 自动滑动
          disableOnInteraction: false
        },
        pagination: {// 如果需要分页器
          el: '.swiper-pagination'
        },
        observer: true, // 启动动态检查器(OB/观众/观看者)
        observeParents: true // 修改swiper的父元素时,自动初始化swiper
        // updateOnImagesReady: true
        // 如果需要前进后退按钮
        // navigation: {
        //   nextEl: '.swiper-button-next',
      //   prevEl: '.swiper-button-prev'
      // }
      // 如果需要滚动条
            // scrollbar: {
            //   el: '.swiper-scrollbar'
            // }
          })
      }
  },
  mounted () {
    this.$http.get('/api/banner/list').then(res => {
      let { data } = res
      if (data.code === 0) {
        this.banner_list = data.data

        // 解决方法: 在获取完数据后,将swiper放在$nextTick下一个UI帧再初始化。

        this.$nextTick(() => {
          this.initSwiper()
        })
        
      }
    })
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/qq_42767631/article/details/84001326
今日推荐