<template>
<div class="carousel">
<transition-group name="fade" tag="div" class="carousel-inner">
<div v-for="(slide, index) in slides" :key="index" v-show="index === currentIndex" class="carousel-item">
<img :src="slide" alt="Carousel Image" />
</div>
</transition-group>
<button @click="prev" class="carousel-control prev">Prev</button>
<button @click="next" class="carousel-control next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
slides: [
'https://via.placeholder.com/800x400?text=Slide+1',
'https://via.placeholder.com/800x400?text=Slide+2',
'https://via.placeholder.com/800x400?text=Slide+3'
],
currentIndex: 0,
interval: null
};
},
methods: {
next() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
}
},
mounted() {
this.interval = setInterval(this.next, 3000);
},
beforeUnmount() {
clearInterval(this.interval);
}
};
</script>
<style scoped>
.carousel {
position: relative;
width: 800px;
height: 400px;
overflow: hidden;
}
.carousel-inner {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-item {
min-width: 100%;
transition: opacity 0.5s ease-in-out;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
opacity: 0;
}
.carousel-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
</style>
模板部分 (<template>):
transition-group 来实现图片的淡入淡出效果。v-for 循环遍历 slides 数组,v-show 控制当前显示的图片。脚本部分 (<script>):
data 中定义了 slides 数组存储图片路径,currentIndex 记录当前显示的图片索引,interval 用于自动切换图片。methods 中定义了 next 和 prev 方法,分别用于切换到下一张和上一张图片。mounted 生命周期钩子中启动自动切换定时器。beforeUnmount 钩子中清除定时器,防止内存泄漏。样式部分 (<style scoped>):
transition 实现图片切换时的动画效果。上一篇::class vue
下一篇:vue 获取页面高度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站