vue.js实现轮播
Vue.js 实现轮播功能
使用第三方库(如 Swiper)
安装 Swiper 库:

npm install swiper
在 Vue 组件中引入 Swiper:

<template>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" :alt="slide.title">
</div>
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</template>
<script>
import Swiper from 'swiper';
import 'swiper/swiper-bundle.css';
export default {
data() {
return {
slides: [
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' }
]
};
},
mounted() {
new Swiper('.swiper-container', {
loop: true,
pagination: {
el: '.swiper-pagination',
clickable: true
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
});
}
};
</script>
纯 Vue.js 实现
通过 Vue 的响应式数据和动态绑定实现轮播:
<template>
<div class="carousel">
<div class="slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
<div class="slide" v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" :alt="slide.title">
</div>
</div>
<button @click="prevSlide">Previous</button>
<button @click="nextSlide">Next</button>
<div class="dots">
<span
v-for="(dot, index) in slides"
:key="index"
@click="goToSlide(index)"
:class="{ active: currentIndex === index }"
></span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' }
]
};
},
methods: {
prevSlide() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
},
nextSlide() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
},
goToSlide(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;
border-radius: 50%;
background: #ccc;
margin: 0 5px;
cursor: pointer;
}
.dots span.active {
background: #333;
}
</style>
自动轮播功能
在纯 Vue 实现的基础上添加自动轮播:
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: 'image1.jpg', title: 'Slide 1' },
{ image: 'image2.jpg', title: 'Slide 2' },
{ image: 'image3.jpg', title: 'Slide 3' }
],
interval: null
};
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.nextSlide();
}, 3000);
},
stopAutoPlay() {
clearInterval(this.interval);
}
},
mounted() {
this.startAutoPlay();
},
beforeDestroy() {
this.stopAutoPlay();
}
};
</script>
注意事项
- 图片路径需要正确配置,可以使用相对路径或完整的 URL
- 轮播的过渡效果可以通过 CSS 的
transition属性调整 - 自动轮播时建议添加鼠标悬停暂停功能,提升用户体验
- 移动端适配需要考虑触摸事件,Swiper 库已内置支持
以上方法提供了从简单到复杂的轮播实现方案,可根据项目需求选择合适的方式。第三方库方案功能更丰富且稳定,纯 Vue 实现更适合学习原理或简单需求。






