vue3+ts实现幻灯片效果

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>
  • startAutoPlaystopAutoPlay函数分别用于开始和停止自动播放。
  • nextSlideprevSlide函数用于切换到下一张或上一张幻灯片,实现了无限循环。
  • 过渡效果通过Vue的<transition>组件实现,定义了进入和离开的动画。
  • 键盘导航通过监听keydown事件实现,当按下左箭头键时调用prevSlide,当按下右箭头键时调用nextSlide
相关推荐
摇滚侠13 小时前
css 设置边框
前端·css
星爷AG I14 小时前
9-24 视觉叙事(AGI基础理论)
前端·人工智能
2501_9400078914 小时前
Flutter for OpenHarmony三国杀攻略App实战 - 鸿蒙适配与打包发布
前端·flutter
css趣多多14 小时前
跨域问题及Vue项目中本地/线上解决方法核心总结
前端
光影少年14 小时前
前端 AIGC
前端·aigc
启山智软14 小时前
供应链商城核心功能模块清单
java·前端·开源
徐同保14 小时前
Claude Code提示词案例(开发复杂动态路由详情页面)
前端
Σdoughty14 小时前
python第三次作业
开发语言·前端·python
是萧萧吖14 小时前
每日一练——有效的括号
java·开发语言·javascript
gpldock22214 小时前
Flutter App Templates Deconstructed: A 2025 Architectural Review
开发语言·javascript·flutter·wordpress