vue.js实现轮播
Vue.js 实现轮播功能
使用第三方库(推荐)
Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。
安装 swiper 和 vue-awesome-swiper:

npm install swiper vue-awesome-swiper
在组件中使用:

<template>
<swiper :options="swiperOptions">
<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>
</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: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' }
],
swiperOptions: {
pagination: { el: '.swiper-pagination' },
loop: true,
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" :alt="slide.title">
</div>
</div>
<button @click="prev">Previous</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
slides: [
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' }
],
currentIndex: 0,
timer: null
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
},
startAutoPlay() {
this.timer = setInterval(this.next, 3000)
},
stopAutoPlay() {
clearInterval(this.timer)
}
},
mounted() {
this.startAutoPlay()
},
beforeDestroy() {
this.stopAutoPlay()
}
}
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
</style>
关键点说明
- 第三方库:
vue-awesome-swiper封装了 Swiper.js,支持手势滑动、分页器、无限循环等高级功能。 - 自定义实现:通过
translateX动态切换幻灯片位置,结合setInterval实现自动播放。 - 响应式设计:确保轮播容器宽度与幻灯片宽度匹配,避免布局错乱。
两种方式均能实现轮播功能,选择取决于项目需求复杂度。第三方库适合功能丰富的场景,自定义实现适合轻量级需求。






