<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);
},
beforeDestroy() {
clearInterval(this.interval);
}
};
</script>
<style scoped>
.carousel {
position: relative;
width: 800px;
height: 400px;
overflow: hidden;
}
.carousel-inner {
display: flex;
}
.carousel-item {
min-width: 100%;
transition: opacity 1s ease-in-out;
}
.carousel-item img {
width: 100%;
height: auto;
}
.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 1s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
opacity: 0;
}
</style>
模板部分 (<template>
):
transition-group
组件来实现轮播图的淡入淡出效果。v-for
指令遍历 slides
数组,显示当前索引对应的图片。脚本部分 (<script>
):
data
中定义了图片数组 slides
和当前显示的索引 currentIndex
。methods
中定义了 next
和 prev
方法,用于切换到下一张或上一张图片。mounted
生命周期钩子中设置了自动切换图片的时间间隔。beforeDestroy
钩子中清除定时器,防止内存泄漏。样式部分 (<style scoped>
):
上一篇:vue启动
下一篇:vue bootstrap
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站