用vue实现图片轮播
使用Vue实现图片轮播
基础实现
创建一个Vue组件,使用v-for循环渲染图片列表,并通过v-bind:class动态控制当前显示的图片。
<template>
<div class="carousel">
<div
v-for="(image, index) in images"
:key="index"
:class="{ 'active': currentIndex === index }"
>
<img :src="image" alt="carousel image">
</div>
<button @click="prev">Previous</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
images: [
'image1.jpg',
'image2.jpg',
'image3.jpg'
],
currentIndex: 0
}
},
methods: {
prev() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.images.length;
}
}
}
</script>
<style>
.carousel div {
display: none;
}
.carousel div.active {
display: block;
}
</style>
自动轮播
添加定时器实现自动轮播功能,注意在组件销毁时清除定时器以避免内存泄漏。
export default {
data() {
return {
// ...其他data
interval: null
}
},
mounted() {
this.startAutoPlay();
},
beforeDestroy() {
clearInterval(this.interval);
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.next();
}, 3000);
}
// ...其他methods
}
}
过渡动画
使用Vue的transition组件添加切换动画效果。
<template>
<div class="carousel">
<transition name="fade" mode="out-in">
<img
:key="currentIndex"
:src="images[currentIndex]"
alt="carousel image"
>
</transition>
<!-- 按钮代码 -->
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
指示器
添加底部小圆点指示器,显示当前图片位置。
<template>
<div class="carousel">
<!-- 图片显示代码 -->
<div class="indicators">
<span
v-for="(image, index) in images"
:key="index"
:class="{ 'active': currentIndex === index }"
@click="currentIndex = index"
></span>
</div>
</div>
</template>
<style>
.indicators span {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background: #ccc;
margin: 0 5px;
cursor: pointer;
}
.indicators span.active {
background: #333;
}
</style>
响应式处理
监听窗口大小变化,调整轮播图尺寸。
export default {
data() {
return {
// ...其他data
windowWidth: 0
}
},
mounted() {
this.windowWidth = window.innerWidth;
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth;
}
// ...其他methods
}
}
使用第三方库
如需更复杂功能,可以考虑使用专门的轮播库如vue-awesome-swiper。
安装:
npm install swiper vue-awesome-swiper
使用:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(image, index) in images" :key="index">
<img :src="image" alt="carousel 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 {
images: ['image1.jpg', 'image2.jpg', 'image3.jpg'],
swiperOptions: {
pagination: {
el: '.swiper-pagination'
},
autoplay: {
delay: 3000
}
}
}
}
}
</script>






