使用vue实现轮播图
使用Vue实现轮播图
基础轮播图实现
安装Vue及相关依赖(如需要过渡效果可引入vue-transition):
npm install vue
创建轮播图组件Carousel.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.alt">
</div>
</div>
<button @click="prev" class="prev">❮</button>
<button @click="next" class="next">❯</button>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: 'path/to/image1.jpg', alt: 'Image 1' },
{ image: 'path/to/image2.jpg', alt: 'Image 2' },
{ image: 'path/to/image3.jpg', alt: 'Image 3' }
]
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
}
}
}
</script>
<style>
.carousel {
position: relative;
overflow: hidden;
width: 100%;
height: 400px;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
.slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
.prev, .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: rgba(0,0,0,0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
.prev { left: 10px; }
.next { right: 10px; }
</style>
自动轮播功能
在组件中添加自动轮播逻辑:

mounted() {
this.startAutoPlay();
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.next();
}, 3000);
},
stopAutoPlay() {
clearInterval(this.interval);
}
},
beforeDestroy() {
this.stopAutoPlay();
}
添加指示器
在模板中添加指示器:
<div class="indicators">
<span
v-for="(slide, index) in slides"
:key="index"
@click="goTo(index)"
:class="{ active: currentIndex === index }"
></span>
</div>
添加样式:

.indicators {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.indicators span {
width: 12px;
height: 12px;
margin: 0 5px;
background: rgba(255,255,255,0.5);
border-radius: 50%;
cursor: pointer;
}
.indicators span.active {
background: white;
}
使用第三方库
如需更复杂功能,可考虑使用专门库:
npm install vue-awesome-swiper
示例用法:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" :alt="slide.alt">
</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: [...],
swiperOptions: {
pagination: { el: '.swiper-pagination' },
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
},
autoplay: { delay: 3000 }
}
}
}
}
</script>






