swiper实现vue轮播
安装 Swiper 依赖
在 Vue 项目中安装 Swiper 核心库和 Vue 组件库:
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="">
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: { Swiper, SwiperSlide },
data() {
return {
slides: [
{ image: 'image1.jpg' },
{ image: 'image2.jpg' }
],
swiperOptions: {
pagination: {
el: '.swiper-pagination'
},
loop: true,
autoplay: {
delay: 3000
}
}
}
}
}
</script>
<style>
.swiper-container {
height: 300px;
}
</style>
常用配置选项
通过修改 swiperOptions 实现不同效果:
swiperOptions: {
// 分页器
pagination: {
el: '.swiper-pagination',
clickable: true
},
// 导航按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
},
// 自动播放
autoplay: {
delay: 2500,
disableOnInteraction: false
},
// 无限循环
loop: true,
// 效果切换
effect: 'fade', // 可选值: slide, fade, cube, coverflow, flip
// 响应式配置
breakpoints: {
640: {
slidesPerView: 1
},
768: {
slidesPerView: 2
}
}
}
自定义样式
在组件中添加对应样式类名:
<template>
<swiper class="custom-swiper">
<!-- ... -->
<div class="swiper-pagination custom-pagination" slot="pagination"></div>
<div class="swiper-button-prev custom-prev" slot="button-prev"></div>
<div class="swiper-button-next custom-next" slot="button-next"></div>
</swiper>
</template>
<style>
.custom-swiper {
--swiper-theme-color: #ff6600;
--swiper-navigation-size: 30px;
}
.custom-pagination {
bottom: 10px;
}
.custom-prev, .custom-next {
background-color: rgba(0,0,0,0.5);
padding: 15px;
border-radius: 50%;
}
</style>
获取 Swiper 实例
通过 ref 获取 Swiper 实例进行控制:
<template>
<swiper ref="mySwiper" @slideChange="onSlideChange">
<!-- ... -->
</swiper>
</template>
<script>
export default {
methods: {
onSlideChange() {
const swiper = this.$refs.mySwiper.$swiper
console.log('当前索引:', swiper.realIndex)
},
nextSlide() {
this.$refs.mySwiper.$swiper.slideNext()
}
}
}
</script>
动态更新内容
当轮播数据变化时调用 update 方法:

watch: {
slides(newVal) {
this.$nextTick(() => {
this.$refs.mySwiper.$swiper.update()
})
}
}






