<template>
<div class="carousel">
<transition-group tag="div" name="fade" 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="prevSlide" class="carousel-control prev"> Prev </button>
<button @click="nextSlide" 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: {
nextSlide() {
this.currentIndex = (this.currentIndex + 1) % this.slides.length;
},
prevSlide() {
this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
}
},
mounted() {
this.interval = setInterval(this.nextSlide, 3000);
},
beforeDestroy() {
clearInterval(this.interval);
}
};
</script>
<style scoped>
.carousel {
position: relative;
width: 800px;
height: 400px;
overflow: hidden;
}
.carousel-inner {
display: flex;
}
.carousel-item {
flex-shrink: 0;
width: 100%;
height: 100%;
}
.carousel-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.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;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
模板部分 (<template>):
transition-group 组件来实现轮播图的淡入淡出效果。v-for 循环遍历 slides 数组,v-show 控制当前显示的图片。脚本部分 (<script>):
slides 数组,存储图片 URL。currentIndex 用来跟踪当前显示的图片索引。nextSlide 和 prevSlide 方法用于切换图片。mounted 生命周期钩子中启动自动切换定时器,在 beforeDestroy 中清除定时器。样式部分 (<style scoped>):
fade-enter-active 和 fade-leave-active 实现淡入淡出效果。上一篇:vue render函数
下一篇:vue3获取组件实例
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站