使用 vue-awesome-swiper 实现轮播图(Vue3实现教程)

一、核心前提:版本适配与安装

1. 版本对应(避免踩坑)

Vue 版本 vue-awesome-swiper 版本 Swiper 版本
Vue3 ^5.0.0 ^8.x
Vue2 ^4.1.1 ^6.x

2. 安装依赖(Vue3 示例)

复制代码
# 安装核心依赖
npm install vue-awesome-swiper@5 swiper@8 --save

二、基础轮播图实现(最简版)

1. 组件内局部引入(推荐)

无需全局注册,仅在需要轮播的组件中引入,减少体积:

复制代码
<template>
  <!-- Swiper 容器:必须设置高度,否则轮播不显示 -->
  <swiper class="swiper-container" :options="swiperOptions">
    <!-- 轮播项 -->
    <swiper-slide v-for="(item, index) in bannerList" :key="index">
      <img :src="item.imgUrl" alt="轮播图" class="slide-img" />
    </swiper-slide>

    <!-- 分页器(圆点):slot 命名为 pagination -->
    <div class="swiper-pagination" slot="pagination"></div>
    <!-- 上/下一页按钮:slot 对应 navigation -->
    <div class="swiper-button-prev" slot="button-prev"></div>
    <div class="swiper-button-next" slot="button-next"></div>
  </swiper>
</template>

<script setup>
import { ref } from 'vue'
// 引入组件和核心样式
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
// 引入所需样式(按需导入,减少体积)
import 'swiper/css' // Swiper 核心样式
import 'swiper/css/pagination' // 分页器样式
import 'swiper/css/navigation' // 导航按钮样式

// 模拟轮播数据
const bannerList = ref([
  { imgUrl: 'https://picsum.photos/1920/500?1' },
  { imgUrl: 'https://picsum.photos/1920/500?2' },
  { imgUrl: 'https://picsum.photos/1920/500?3' }
])

// Swiper 核心配置
const swiperOptions = ref({
  // 基础配置
  loop: true, // 循环播放(必备,否则轮播到最后一页会停止)
  autoplay: {
    delay: 3000, // 自动播放间隔(毫秒)
    disableOnInteraction: false // 点击轮播后仍继续自动播放
  },
  speed: 500, // 切换动画速度(毫秒)
  // 分页器配置
  pagination: {
    el: '.swiper-pagination', // 绑定分页器 DOM 元素
    clickable: true // 分页圆点可点击切换
  },
  // 导航按钮配置
  navigation: {
    nextEl: '.swiper-button-next', // 下一页按钮
    prevEl: '.swiper-button-prev'  // 上一页按钮
  }
})
</script>

<style scoped>
/* 轮播容器:必须设置高度 */
.swiper-container {
  width: 100%;
  height: 500px; /* 根据设计需求调整 */
}

/* 轮播图自适应 */
.slide-img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持比例,裁剪溢出部分 */
}

/* 样式穿透:修改分页器/导航按钮样式(scoped 下必须加 :deep) */
:deep(.swiper-pagination-bullet) {
  width: 12px;
  height: 12px;
  background: #fff;
  opacity: 0.5;
}
:deep(.swiper-pagination-bullet-active) {
  opacity: 1;
  background: #409eff; /* 激活态颜色 */
}
:deep(.swiper-button-prev),
:deep(.swiper-button-next) {
  color: #fff; /* 导航按钮颜色 */
}
</style>

2. 全局引入(可选,多页面复用)

若多个组件需要轮播,可在 main.js 全局注册:

复制代码
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css'
import 'swiper/css/pagination'
import 'swiper/css/navigation'

const app = createApp(App)
// 全局注册组件
app.component('Swiper', Swiper)
app.component('SwiperSlide', SwiperSlide)
app.mount('#app')

三、关键配置说明(常用)

配置项 类型 作用 示例值
loop Boolean 是否循环播放 true(推荐)
autoplay Object 自动播放配置 { delay: 3000, disableOnInteraction: false }
direction String 轮播方向:水平 / 垂直 horizontal/vertical
pagination.type String 分页器类型:圆点 / 进度条 / 分数 bullets/progressbar/fraction
spaceBetween Number 轮播项之间的间距(像素) 10(多列轮播时用)
slidesPerView Number 同时显示的轮播项数量(多列轮播) 3
mousewheel Boolean 是否支持鼠标滚轮控制轮播 true

四、高级功能实现

1. 手动控制轮播(切换 / 暂停 / 播放)

通过 ref 获取 Swiper 实例,实现手动控制:

复制代码
<template>
  <div>
    <swiper ref="swiperRef" :options="swiperOptions" class="swiper-container">
      <swiper-slide v-for="item in bannerList" :key="item.id">
        <img :src="item.imgUrl" alt="" />
      </swiper-slide>
    </swiper>
    <!-- 手动控制按钮 -->
    <div class="control-btn-group">
      <button @click="prevSlide">上一页</button>
      <button @click="toggleAutoplay">{{ isPlay ? '暂停' : '播放' }}</button>
      <button @click="nextSlide">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css'

const swiperRef = ref(null) // 绑定 Swiper 实例
const isPlay = ref(true) // 自动播放状态
const bannerList = ref([/* 轮播数据 */])
const swiperOptions = ref({
  loop: true,
  autoplay: { delay: 3000 },
})

// 上一页
const prevSlide = () => {
  swiperRef.value.swiper.slidePrev()
}
// 下一页
const nextSlide = () => {
  swiperRef.value.swiper.slideNext()
}
// 切换自动播放
const toggleAutoplay = () => {
  const swiper = swiperRef.value.swiper
  if (swiper.autoplay.running) {
    swiper.autoplay.stop()
    isPlay.value = false
  } else {
    swiper.autoplay.start()
    isPlay.value = true
  }
}
</script>

2. 动态加载轮播数据(接口请求)

适配异步获取轮播数据的场景,确保数据加载后轮播正常渲染:

复制代码
<template>
  <swiper :options="swiperOptions" class="swiper-container" v-if="bannerList.length">
    <swiper-slide v-for="item in bannerList" :key="item.id">
      <img :src="item.imgUrl" alt="" />
    </swiper-slide>
    <div class="swiper-pagination" slot="pagination"></div>
  </swiper>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css'
import 'swiper/css/pagination'

const bannerList = ref([])
const swiperOptions = ref({
  loop: true,
  autoplay: { delay: 3000 },
  pagination: { el: '.swiper-pagination', clickable: true }
})

// 模拟接口请求轮播数据
const fetchBanner = async () => {
  // 替换为真实接口
  const res = await fetch('/api/banner')
  const data = await res.json()
  bannerList.value = data.list
}

onMounted(() => {
  fetchBanner()
})
</script>

3. 垂直轮播(纵向滚动)

仅需修改 direction 配置,适配垂直轮播场景(如公告栏):

复制代码
const swiperOptions = ref({
  direction: 'vertical', // 垂直方向
  loop: true,
  autoplay: { delay: 2000 },
  pagination: { el: '.swiper-pagination' }
})

4. 多列轮播(同时显示多个轮播项)

通过 slidesPerViewspaceBetween 实现多列轮播:

js

复制代码
const swiperOptions = ref({
  loop: true,
  autoplay: { delay: 2000 },
  slidesPerView: 3, // 同时显示3个轮播项
  spaceBetween: 10, // 轮播项间距10px
  pagination: { el: '.swiper-pagination', clickable: true }
})

五、常见问题解决

1. 轮播图不显示?

  • 必设 swiper-container 的高度(如 height: 500px);
  • 确保 loop: true(非循环模式下数据少可能不显示);
  • 检查样式是否引入(至少引入 swiper/css)。

2. 样式穿透不生效?

Vue3 中 scoped 样式下,修改 Swiper 内置样式需用 :deep()

复制代码
:deep(.swiper-pagination-bullet-active) {
  background: #ff0;
}

3. 自动播放点击后停止?

设置 autoplay.disableOnInteraction: false,避免交互后停止自动播放。

4. 动态数据加载后轮播异常?

  • v-if="bannerList.length" 确保数据加载后再渲染 Swiper;
  • 数据更新后调用 swiperRef.value.swiper.update() 更新布局。

六、总结

使用 vue-awesome-swiper 实现轮播的核心步骤:

  1. 安装对应版本的依赖(Vue3 → v5 + Swiper8);
  2. 引入组件和所需样式(核心样式 + 分页 / 导航样式);
  3. 配置 swiperOptions(必配 loop + autoplay,按需配分页 / 导航);
  4. 编写轮播结构(swiper 容器 + swiper-slide 轮播项);
  5. 适配样式(设置容器高度、样式穿透修改内置样式)。

进阶场景可通过 ref 获取 Swiper 实例实现手动控制,或结合接口请求动态加载数据,满足不同业务需求。

相关推荐
小小码农一只1 小时前
Spring WebFlux与响应式编程:构建高效的异步Web应用
java·前端·spring·spring webflux
W.Y.B.G1 小时前
vue3项目中集成高德地图使用示例
前端·javascript·网络
王兆龙1681 小时前
简易版增删改查
前端·vscode·vue
Jonathan Star1 小时前
`npx prettier --write . --end-of-line lf` 是一条用于**格式化代码**的命令
前端·css3
pan3035074791 小时前
Tailwind CSS 实战
前端·tailwind
_lst_1 小时前
系统环境变量
前端·chrome
哈哈~haha1 小时前
ui5_Walkthrough_Step 4: XML 视图
xml·前端
江公望1 小时前
CSS variable 10分钟讲清楚
前端·css
YAY_tyy1 小时前
基于矩形区域的相机自动定位与飞行控制实现
前端·javascript·3d·cesium