1.安装插件

安装插件vue-awesome-swiper

npm i swiper vue-awesome-swiper

安装插件swiper

npm i swiper@5
查看package.json  这样就是安装完成

2.代码使用

2.1新建swiper组件  swiper.vue
<template>
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="(item, index) in imgs" :key="index">
        <img :src="item.pic" />
      </div>
    </div>
    <div class="swiper-pagination"></div>
    <!-- <div class="swiper-button-prev custom-prev"></div>
    <div class="swiper-button-next custom-next"></div> -->
  </div>
</template>
<script setup>
import { reactive, onMounted } from "vue";
import Swiper from "swiper"; // 引入库
import "swiper/css/swiper.css"; // 引入样式文件 注意5和6版本的样式文件不一致
const imgs = reactive([
  { pic: require("@/assets/img/index-banner-01.jpeg") },
  { pic: require("@/assets/img/index-banner-03.jpg") },
]);
onMounted(() => {
  const mySwiper = new Swiper(".swiper-container", {
    loop: true, // 循环模式选项
    autoplay: true, //自动滚动
    effect: "fade", //渐变切换
    autoplay: {
      delay: 3000, //3秒切换一次
      pauseOnMouseEnter: true, //鼠标移入 轮播暂停
    },
    pagination: {
    el: '.swiper-pagination',
    type: 'bullets',
    clickable: true,
  },
    // navigation: {
    //   nextEl: '.swiper-button-next',
    //   prevEl: '.swiper-button-prev',
    // }
  });
});
</script>
<style lang="scss">
.swiper-container {
  width: 100%;
  //   height: 300px;
  .swiper-slide {
    width: 100% !important;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}
</style>
Error: Can‘t resolve ‘swiper/css/swiper.css‘ 如何解决

解决方案: 在引入的文件中将其改为:import 'swiper/swiper-bundle.css'

2.2在你要使用的地方引入
<template>
  <div class="common-layout">
      <swiperCom />
    </div>
</template>

<script setup>
    import swiperCom from '@/components/swiper.vue';
</script>

<style lang="scss">
 
</style>

3.swiper的参数

  • slidesPerView:每次显示几个轮播图
  • spaceBetween:每个轮播图之间的间距(单位:px)
  • loop:是否循环滚动
  • centeredSlides:是否居中对齐(true:居中,false:左对齐),默认 false 左对齐,
  • autoplay:是否自动播放
  • navigation:是否左右切换箭头
  • pagination:分页配置
    • clickable:在点击分页圆点的时候,是否进行切换
  • scrollbar:显示滚动条
    • draggable:滚动条可拖动
  • autoplay:切换图片的频率(毫秒为单位)
    • delay:切换的时间(单位:毫秒ms)
    • disableOnInteraction:滑动图片后不禁用自动播放 delay: 2500, disableOnInteraction: false,

其他参数详情请参考官方 API  https://swiperjs.com/swiper-apiicon-default.png?t=N7T8https://swiperjs.com/swiper-api 

Logo

前往低代码交流专区

更多推荐