用vue实现轮播
使用 Vue 实现轮播
使用 Vue 原生实现轮播
创建一个简单的轮播组件,通过动态绑定 v-for 和 v-show 控制显示当前幻灯片。
模板部分:
<template>
<div class="carousel">
<div class="slides">
<div
v-for="(slide, index) in slides"
:key="index"
class="slide"
v-show="currentIndex === index"
>
<img :src="slide.image" :alt="slide.alt">
</div>
</div>
<button @click="prevSlide">Previous</button>
<button @click="nextSlide">Next</button>
</div>
</template>
脚本部分:
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: 'image1.jpg', alt: 'Image 1' },
{ image: 'image2.jpg', alt: 'Image 2' },
{ image: 'image3.jpg', alt: 'Image 3' }
]
};
},
methods: {
nextSlide() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
},
prevSlide() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
}
}
};
</script>
样式部分:
<style>
.carousel {
position: relative;
width: 100%;
max-width: 800px;
margin: 0 auto;
}
.slide {
width: 100%;
height: 400px;
overflow: hidden;
}
.slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
使用第三方库(如 Swiper)
安装 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.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: [
{ image: 'image1.jpg', alt: 'Image 1' },
{ image: 'image2.jpg', alt: 'Image 2' },
{ image: 'image3.jpg', alt: 'Image 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>
自动轮播功能
在原生实现中,可以添加 setInterval 实现自动轮播:
mounted() {
this.autoPlay = setInterval(() => {
this.nextSlide();
}, 3000);
},
beforeDestroy() {
clearInterval(this.autoPlay);
}
添加过渡动画
使用 Vue 的 <transition> 组件为轮播添加平滑过渡效果:
<transition name="fade" mode="out-in">
<div
v-for="(slide, index) in slides"
:key="index"
class="slide"
v-show="currentIndex === index"
>
<img :src="slide.image" :alt="slide.alt">
</div>
</transition>
CSS 过渡样式:
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
以上方法提供了从基础到进阶的 Vue 轮播实现方案,可根据项目需求选择合适的方式。原生实现适合简单需求,而 Swiper 提供了更丰富的功能和更好的移动端支持。







