<template>
<div class="carousel">
<transition-group name="fade" tag="div" class="carousel-images">
<div v-for="(image, index) in images" :key="index" v-show="index === currentIndex" class="carousel-image">
<img :src="image" alt="carousel image" />
</div>
</transition-group>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
<script>
import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const images = [
'https://via.placeholder.com/150',
'https://via.placeholder.com/151',
'https://via.placeholder.com/152'
];
const currentIndex = ref(0);
let intervalId;
const prev = () => {
currentIndex.value = (currentIndex.value - 1 + images.length) % images.length;
};
const next = () => {
currentIndex.value = (currentIndex.value + 1) % images.length;
};
const startAutoPlay = () => {
intervalId = setInterval(() => {
next();
}, 3000);
};
const stopAutoPlay = () => {
clearInterval(intervalId);
};
onMounted(() => {
startAutoPlay();
});
onUnmounted(() => {
stopAutoPlay();
});
return {
images,
currentIndex,
prev,
next
};
}
};
</script>
<style scoped>
.carousel {
position: relative;
width: 300px;
margin: 0 auto;
}
.carousel-images {
display: flex;
overflow: hidden;
}
.carousel-image {
flex-shrink: 0;
width: 100%;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
button {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
button:first-of-type {
left: 10px;
}
button:last-of-type {
right: 10px;
}
</style>
模板部分 (<template>):
transition-group 来实现图片切换时的淡入淡出效果。v-for 遍历 images 数组,显示当前索引对应的图片。脚本部分 (<script>):
setup)。images 和当前显示的图片索引 currentIndex。prev 和 next 方法用于手动切换图片。setInterval 实现自动播放功能,并在组件挂载和卸载时分别启动和停止自动播放。样式部分 (<style scoped>):
上一篇:vue3定义变量
下一篇:vue3 leaflet
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站