vue 轮播图实现
Vue 轮播图实现方法
使用第三方库(推荐)
安装 swiper 或 vue-awesome-swiper 库:
npm install swiper vue-awesome-swiper
基础实现代码(以 vue-awesome-swiper 为例):

<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" />
</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' },
{ image: 'image3.jpg' }
],
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
autoplay: {
delay: 3000
}
}
}
}
}
</script>
原生实现方案
通过 Vue 的响应式特性手动实现轮播:

<template>
<div class="carousel">
<div class="slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
<div v-for="(slide, index) in slides" :key="index" class="slide">
<img :src="slide.image" />
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: 'image1.jpg' },
{ image: 'image2.jpg' },
{ image: 'image3.jpg' }
]
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
}
},
mounted() {
setInterval(this.next, 3000)
}
}
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
</style>
关键实现要点
轮播图核心逻辑需要处理自动播放、无限循环和手势滑动(移动端)。第三方库通常已内置这些功能,原生实现需注意:
- 使用 CSS transform 实现平滑过渡
- 通过模运算实现无限循环
- 清除定时器防止内存泄漏
- 添加 touch 事件支持移动端滑动
性能优化建议:
- 图片预加载
- 懒加载非当前可见项
- 合理设置过渡动画时间(通常 300-500ms)






