vue
复制代码
<template>
<div class="ppt" @keydown.left="prevSlide" @keydown.right="nextSlide">
<transition name="slide">
<div v-if="currentSlideIndex === index" v-for="(slide, index) in slides" :key="index">
{{ slide }}
</div>
</transition>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
const slides = ref(['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5']);
const currentSlideIndex = ref(0);
// 自动播放
let autoPlayTimer: number | null = null;
const startAutoPlay = () => {
autoPlayTimer = setInterval(() => {
nextSlide();
}, 3000);
};
const stopAutoPlay = () => {
if (autoPlayTimer) {
clearInterval(autoPlayTimer);
autoPlayTimer = null;
}
};
onMounted(() => {
startAutoPlay();
});
onUnmounted(() => {
stopAutoPlay();
});
// 切换幻灯片
const nextSlide = () => {
currentSlideIndex.value = (currentSlideIndex.value + 1) % slides.value.length;
};
const prevSlide = () => {
currentSlideIndex.value = (currentSlideIndex.value - 1 + slides.value.length) % slides.value.length;
};
</script>
<style>
.slide-enter-active,
.slide-leave-active {
transition: all 0.5s ease;
}
.slide-enter-from,
.slide-leave-to {
opacity: 0;
transform: translateX(30px);
}
</style>