轮播vue实现
使用 Vue 实现轮播功能
基础轮播实现
安装依赖(如使用 Swiper):
npm install swiper vue-awesome-swiper
组件代码示例:
<template>
<swiper :options="swiperOption">
<swiper-slide v-for="(item, index) in slides" :key="index">
<img :src="item.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: require('@/assets/slide1.jpg') },
{ image: require('@/assets/slide2.jpg') }
],
swiperOption: {
pagination: {
el: '.swiper-pagination'
},
autoplay: {
delay: 3000
},
loop: true
}
}
}
}
</script>
自定义简单轮播
无依赖实现方案:
<template>
<div class="carousel">
<div class="slides" :style="slideStyle">
<div v-for="(slide, index) in slides" :key="index" class="slide">
<img :src="slide.image" alt="">
</div>
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
slides: [
{ image: require('@/assets/slide1.jpg') },
{ image: require('@/assets/slide2.jpg') }
]
}
},
computed: {
slideStyle() {
return {
transform: `translateX(-${this.currentIndex * 100}%)`
}
}
},
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;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%;
}
</style>
自动轮播功能
添加自动播放逻辑:
export default {
// ...其他代码
mounted() {
this.startAutoPlay()
},
beforeDestroy() {
this.stopAutoPlay()
},
methods: {
startAutoPlay() {
this.interval = setInterval(() => {
this.next()
}, 3000)
},
stopAutoPlay() {
clearInterval(this.interval)
}
}
}
过渡动画优化
使用 Vue 过渡效果:
<template>
<transition-group name="slide" tag="div" class="carousel">
<div v-for="(slide, index) in slides"
v-show="index === currentIndex"
:key="index"
class="slide">
<img :src="slide.image" alt="">
</div>
</transition-group>
</template>
<style>
.slide-enter-active, .slide-leave-active {
transition: opacity 0.5s ease;
}
.slide-enter, .slide-leave-to {
opacity: 0;
}
</style>
响应式处理
添加窗口大小监听:
export default {
// ...其他代码
data() {
return {
windowWidth: 0
}
},
mounted() {
this.windowWidth = window.innerWidth
window.addEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth
}
}
}






