vue swiper 轮播实现
Vue Swiper 轮播实现
安装 Swiper 依赖
确保项目已安装 swiper 和 vue-awesome-swiper(适用于 Vue 2/3)。通过以下命令安装:
npm install swiper vue-awesome-swiper
基础轮播配置
在 Vue 组件中引入 Swiper 并配置基础轮播:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(item, index) in slides" :key="index">
<img :src="item.image" alt="Slide">
</swiper-slide>
<!-- 分页器 -->
<div class="swiper-pagination" slot="pagination"></div>
<!-- 导航按钮 -->
<div class="swiper-button-prev" slot="button-prev"></div>
<div class="swiper-button-next" slot="button-next"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/swiper-bundle.min.css'
export default {
components: { Swiper, SwiperSlide },
data() {
return {
slides: [
{ image: 'https://via.placeholder.com/800x400' },
{ image: 'https://via.placeholder.com/800x400' }
],
swiperOptions: {
pagination: { el: '.swiper-pagination' },
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
},
loop: true,
autoplay: { delay: 3000 }
}
}
}
}
</script>
自定义样式
通过 CSS 调整轮播样式,例如修改分页器颜色或导航按钮位置:
<style scoped>
.swiper-container {
width: 100%;
height: 400px;
}
.swiper-pagination-bullet-active {
background: #ff0000;
}
.swiper-button-next, .swiper-button-prev {
color: #fff;
}
</style>
动态加载数据
若需异步加载轮播数据,可在 mounted 或通过 API 更新 slides 数据:
export default {
methods: {
fetchSlides() {
// 模拟 API 请求
setTimeout(() => {
this.slides = [
{ image: 'https://via.placeholder.com/800x400/0000ff' },
{ image: 'https://via.placeholder.com/800x400/00ff00' }
]
}, 1000)
}
},
mounted() {
this.fetchSlides()
}
}
响应式配置
根据屏幕尺寸调整轮播参数,使用 breakpoints 配置:

swiperOptions: {
breakpoints: {
640: { slidesPerView: 1 },
768: { slidesPerView: 2 },
1024: { slidesPerView: 3 }
}
}
注意事项
- 确保引入的 CSS 文件路径正确,若使用 Swiper 6+,需引入
swiper/swiper-bundle.min.css。 - 若需使用 Swiper 的模块(如缩略图、滚动条),需单独导入并注册。
- Vue 3 项目需确认
vue-awesome-swiper版本兼容性,或直接使用 Swiper 官方 Vue 组件。






