Vue轮播图(swiper)

注意:swiper版本为5.x.x时,import才能引入成功

1. 在terminal中输入,引入swiper依赖

-- npm install swiper

2. 新建一个Banner.vue文件

<template>
  <div class="banner">
    <div class="swiper-container">
      <div class="swiper-wrapper">
        <div class="swiper-slide" v-for="(item,index) in banners" :key="index">
          <img :src="item.pic" />
        </div>
        <!-- 如果需要分页器 -->
        <div class="swiper-pagination"></div>
        <!-- 如果需要导航按钮 -->
        <div class="swiper-button-prev"></div>
        <div class="swiper-button-next"></div>
        <!-- 如果需要滚动条 -->
        <div class="swiper-scrollbar"></div>
      </div>
    </div>
  </div>
</template>

<script>
//引入依赖
import Swiper from "swiper";
export default {
  props: {
    'banners': {
      type: Array,
      default: () => [],
    },
  },
  methods: {
    initBanner() {
      new Swiper(".swiper-container", {
        direction: "horizontal", // 垂直切换选项
        loop: true, // 循环模式选项
        // 如果需要分页器
        pagination: {
          el: ".swiper-pagination",
        },
        navigation: {
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev",
        },
        // 如果需要滚动条
        scrollbar: {
          el: ".swiper-scrollbar",
        },
      });
    },
  },
  mounted() {
    this.initBanner();
  },
  watch: {
    banners() {
      //banners改变 网络请求数据已经成功 之后进行初始化操作
      this.$nextTick(() => {
        this.initBanner();
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../style/index.less";
@import "~swiper/css/swiper.min.css";

.swiper-container {
  .w(375);
  .h(150);
  background: green;
  img {
    .w(375);
    .h(150);
  }
}
</style>
Logo

前往低代码交流专区

更多推荐