vue实现轮播图动画
使用 Vue 实现轮播图动画
基础轮播图实现
安装依赖(如需要)
npm install vue-awesome-swiper
基础模板结构
<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(slide, index) in slides" :key="index">
<img :src="slide.image" alt="">
</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: '/path/to/image1.jpg' },
{ image: '/path/to/image2.jpg' }
],
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
loop: true,
autoplay: {
delay: 3000
}
}
}
}
}
</script>
自定义动画效果
CSS过渡动画
.swiper-slide {
transition: transform 0.5s ease-in-out;
}
.swiper-slide-active {
transform: scale(1.05);
}
JavaScript动画钩子
swiperOption: {
on: {
slideChangeTransitionStart: function() {
// 动画开始时的处理
},
slideChangeTransitionEnd: function() {
// 动画结束时的处理
}
}
}
纯Vue实现(不使用第三方库)
基础实现代码
<template>
<div class="carousel">
<div class="slides" :style="slideStyle">
<div v-for="(slide, index) in slides"
:key="index"
class="slide">
<img :src="slide.image">
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: '/path/to/image1.jpg' },
{ image: '/path/to/image2.jpg' }
]
}
},
computed: {
slideStyle() {
return {
transform: `translateX(-${this.currentIndex * 100}%)`,
transition: 'transform 0.5s ease-in-out'
}
}
},
methods: {
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length
}
}
}
</script>
<style>
.carousel {
overflow: hidden;
position: relative;
}
.slides {
display: flex;
width: 100%;
}
.slide {
flex-shrink: 0;
width: 100%;
}
</style>
高级动画效果
淡入淡出效果
.slide {
position: absolute;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slide.active {
opacity: 1;
}
3D翻转效果
.slide {
transform-style: preserve-3d;
transition: transform 1s;
}
.slide.active {
transform: rotateY(0deg);
}
.slide.next {
transform: rotateY(180deg);
}
自动轮播实现
添加自动轮播功能
export default {
mounted() {
this.startAutoPlay()
},
beforeDestroy() {
this.stopAutoPlay()
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.next()
}, 3000)
},
stopAutoPlay() {
clearInterval(this.interval)
}
}
}






