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

vue3 轮播图

作者:潮起潮落   发布日期:2026-03-03   浏览:96

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

<script>
import { ref, onMounted, onUnmounted } from 'vue';

export default {
  setup() {
    const images = [
      'https://via.placeholder.com/150',
      'https://via.placeholder.com/151',
      'https://via.placeholder.com/152'
    ];
    const currentIndex = ref(0);
    let intervalId;

    const prev = () => {
      currentIndex.value = (currentIndex.value - 1 + images.length) % images.length;
    };

    const next = () => {
      currentIndex.value = (currentIndex.value + 1) % images.length;
    };

    const startAutoPlay = () => {
      intervalId = setInterval(() => {
        next();
      }, 3000);
    };

    const stopAutoPlay = () => {
      clearInterval(intervalId);
    };

    onMounted(() => {
      startAutoPlay();
    });

    onUnmounted(() => {
      stopAutoPlay();
    });

    return {
      images,
      currentIndex,
      prev,
      next
    };
  }
};
</script>

<style scoped>
.carousel {
  position: relative;
  width: 300px;
  margin: 0 auto;
}

.carousel-images {
  display: flex;
  overflow: hidden;
}

.carousel-image {
  flex-shrink: 0;
  width: 100%;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
}

button:first-of-type {
  left: 10px;
}

button:last-of-type {
  right: 10px;
}
</style>

解释说明:

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

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

    • 使用 Vue 3 的组合式 API (setup)。
    • 定义了图片数组 images 和当前显示的图片索引 currentIndex
    • 实现了 prevnext 方法用于手动切换图片。
    • 使用 setInterval 实现自动播放功能,并在组件挂载和卸载时分别启动和停止自动播放。
  3. 样式部分 (<style scoped>):

    • 设置轮播图容器的样式,确保图片居中显示。
    • 定义淡入淡出的过渡效果。
    • 设置按钮的样式并将其定位在图片两侧。

上一篇:vue3定义变量

下一篇:vue3 leaflet

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

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

Laravel 中文站