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

vue 轮播图

作者:萫蕉姺森う   发布日期:2025-08-30   浏览:47

<template>
  <div class="carousel">
    <transition-group name="fade" tag="div" class="carousel-inner">
      <div v-for="(slide, index) in slides" :key="index" v-show="index === currentIndex" class="carousel-item">
        <img :src="slide" alt="carousel image" />
      </div>
    </transition-group>
    <button @click="prev" class="carousel-control prev">Prev</button>
    <button @click="next" class="carousel-control next">Next</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      slides: [
        '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.slides.length;
    },
    prev() {
      this.currentIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
    }
  },
  mounted() {
    this.interval = setInterval(this.next, 3000);
  },
  beforeDestroy() {
    clearInterval(this.interval);
  }
};
</script>

<style scoped>
.carousel {
  position: relative;
  width: 800px;
  height: 400px;
  overflow: hidden;
}
.carousel-inner {
  display: flex;
}
.carousel-item {
  min-width: 100%;
  transition: opacity 1s ease-in-out;
}
.carousel-item img {
  width: 100%;
  height: auto;
}
.carousel-control {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
}
.prev {
  left: 10px;
}
.next {
  right: 10px;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 1s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>

解释说明:

  1. 模板部分 (<template>)

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

    • data 中定义了图片数组 slides 和当前显示的索引 currentIndex
    • methods 中定义了 nextprev 方法,用于切换到下一张或上一张图片。
    • mounted 生命周期钩子中设置了自动切换图片的时间间隔。
    • beforeDestroy 钩子中清除定时器,防止内存泄漏。
  3. 样式部分 (<style scoped>)

    • 定义了轮播图容器、图片和控制按钮的样式。
    • 使用 CSS 过渡效果实现了淡入淡出动画。

上一篇:vue启动

下一篇:vue bootstrap

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

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

Laravel 中文站