Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue3轮播图

作者:花小泽ノ   发布日期:2025-07-24   浏览:73

<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>

解释说明

  1. 模板部分 (<template>):

    • 使用 transition-group 组件来创建动画效果。
    • v-for 指令遍历 images 数组,显示当前索引对应的图片。
    • 提供了两个按钮用于手动切换轮播图。
  2. 脚本部分 (<script>):

    • 定义了 images 数组存储轮播图的图片链接。
    • currentIndex 用于跟踪当前显示的图片索引。
    • next()prev() 方法用于切换到下一张或上一张图片。
    • mounted 生命周期钩子中设置定时器,每 3 秒自动切换到下一张图片。
    • beforeUnmount 中清除定时器以避免内存泄漏。
  3. 样式部分 (<style scoped>):

    • 设置轮播图容器和图片的基本样式。
    • 使用 CSS 过渡动画 (transition) 实现平滑的滑动效果。

上一篇:vue使用websocket

下一篇:vue界面转为静态html

大家都在看

vue.config.js configu

node.js vue

vue 图表组件

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站