轮播图swiper

利用swiper制作轮播图

(1)安装swiper插件,npm i --save swiper@5

(2)引包(在需要轮播图的组件中的script中引入,该项目中是Carousel)

在入口文件引入swiper样式

 

(3)在页面结构,即轮播图完整的前提下,new Swiper

***如何判断轮播图结构完整:

通过watch数据监听,监听已有数据的变化(监听轮播图中的数据已经更新);但是这无法保证v-for已经执行完毕,需要利用组件实例对象身上的$nextTick()

nextTick原理:在下次DOM更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的DOM。

这样可以等到v-for结束之后再执行里面的回调函数,保证页面结构是完整的

<template>
  <div class="swiper-container" ref="cur">
    <div class="swiper-wrapper">
      <div
        class="swiper-slide"
        v-for="(carousel, index) in list"
        :key="carousel.id"
      >
        <img src="carousel.imgUrl" />
      </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>

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

<script>
// 引入swiper
import Swiper from 'swiper'
export default {
  name:'carousel',
  props:['list'],
  watch:{
    // 监听bannerList数据的变化,因为这条数据由空数组变为数组里由四个元素
    list:{
      immediate:true,
      handler(newValue,oldValue){
        // 如果执行handler方法,代表组件实例对象身上这个属性已经有属性值了,(数组中包含四个元素)
        // 但是当前这个函数执行,只能保证bannerList的数据已经有了,但是不能保证v-for已经执行结束了
        // 然而,v-for执行完毕,才会有完整的结构
        // 可以使用nextTick解决这个问题,其定义是,在下次DOM更新,循环结束之后,执行延迟回调,在修改数据之后,立即使用这个方法,获取更新后的DOM
        this.$nextTick(()=>{
          // 当执行这个回调函数的时候,能保证服务器的数据回来了,v-for执行完毕了,即轮播图需要的结构已经完整了
          var mySwiper=new Swiper(
            this.$refs.cur,
            {
              loop:true,
              pagination:{
                el:".swiper-pagination",
                clickable:true,
              },
              navigation:{
                nextEl:'.swiper-button-next',
                prevEl:'.swiper-button-prev'
              }
            }
          )
        })
      }
    }
  }
};
</script>

 

posted @ 2022-05-22 22:34  yeqi7  阅读(173)  评论(0)    收藏  举报