<template>
<div class="carousel">
<transition-group name="slide" tag="div" class="carousel-inner">
<div v-for="(item, index) in images" :key="index" v-show="index === currentIndex" class="carousel-item">
<img :src="item" alt="carousel image" />
</div>
</transition-group>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
export default {
data() {
return {
images: [
'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.images.length;
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
}
},
mounted() {
this.interval = setInterval(() => {
this.next();
}, 3000);
},
beforeUnmount() {
clearInterval(this.interval);
}
};
</script>
<style scoped>
.carousel {
position: relative;
width: 800px;
margin: 0 auto;
}
.carousel-inner {
overflow: hidden;
}
.carousel-item {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.slide-enter-active,
.slide-leave-active {
transition: transform 0.5s ease;
}
.slide-enter-from {
transform: translateX(100%);
}
.slide-enter-to {
transform: translateX(0);
}
.slide-leave-from {
transform: translateX(0);
}
.slide-leave-to {
transform: translateX(-100%);
}
</style>
模板部分 (<template>
):
transition-group
组件来创建动画效果。v-for
指令遍历 images
数组,显示当前索引对应的图片。脚本部分 (<script>
):
images
数组存储轮播图的图片链接。currentIndex
用于跟踪当前显示的图片索引。next()
和 prev()
方法用于切换到下一张或上一张图片。mounted
生命周期钩子中设置定时器,每 3 秒自动切换到下一张图片。beforeUnmount
中清除定时器以避免内存泄漏。样式部分 (<style scoped>
):
transition
) 实现平滑的滑动效果。上一篇:vue使用websocket
下一篇:vue界面转为静态html
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站