vue实现轮播图源码
Vue 轮播图实现方法
使用 Vue 实现轮播图可以通过原生开发或借助第三方库(如 Swiper)完成。以下是两种常见实现方式:
原生 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" :alt="slide.title">
</div>
</div>
<button @click="prev">上一张</button>
<button @click="next">下一张</button>
<div class="dots">
<span
v-for="(dot, index) in slides"
:key="index"
@click="goTo(index)"
:class="{ active: currentIndex === index }"
></span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: 'image1.jpg', title: '图片1' },
{ image: 'image2.jpg', title: '图片2' },
{ image: 'image3.jpg', title: '图片3' }
]
}
},
methods: {
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
},
goTo(index) {
this.currentIndex = index;
}
}
}
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
.dots span {
display: inline-block;
width: 10px;
height: 10px;
margin: 0 5px;
background: #ccc;
border-radius: 50%;
cursor: pointer;
}
.dots span.active {
background: #333;
}
</style>
关键点:

- 使用
translateX实现横向滑动效果 - 通过
currentIndex控制当前显示项 - 添加过渡动画提升用户体验
- 实现无限循环轮播逻辑
使用 Swiper 库实现
安装 Swiper:
npm install swiper vue-awesome-swiper
组件代码:

<template>
<swiper :options="swiperOptions" ref="mySwiper">
<swiper-slide v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" :alt="slide.title">
</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/css/swiper.css'
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
slides: [
{ image: 'image1.jpg', title: '图片1' },
{ image: 'image2.jpg', title: '图片2' },
{ image: 'image3.jpg', title: '图片3' }
],
swiperOptions: {
pagination: {
el: '.swiper-pagination',
clickable: true
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
},
loop: true,
autoplay: {
delay: 3000,
disableOnInteraction: false
}
}
}
}
}
</script>
Swiper 优势:
- 内置丰富的过渡效果
- 支持触摸滑动
- 自动轮播配置简单
- 响应式设计支持
- 丰富的 API 和事件系统
实现自动轮播
对于原生实现,可添加以下代码:
mounted() {
this.autoPlay = setInterval(() => {
this.next();
}, 3000);
},
beforeDestroy() {
clearInterval(this.autoPlay);
}
对于 Swiper 版本,只需配置 autoplay 选项即可实现自动轮播功能。
两种方式各有优劣:原生实现更轻量且可控,适合简单需求;Swiper 提供更多现成功能和更好的移动端支持,适合复杂场景。






