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>
startAutoPlay
和stopAutoPlay
函数分别用于开始和停止自动播放。nextSlide
和prevSlide
函数用于切换到下一张或上一张幻灯片,实现了无限循环。- 过渡效果通过Vue的
<transition>
组件实现,定义了进入和离开的动画。 - 键盘导航通过监听
keydown
事件实现,当按下左箭头键时调用prevSlide
,当按下右箭头键时调用nextSlide
。