当前位置:首页 > VUE

vue实现信号灯

2026-02-23 21:04:22VUE

Vue 实现信号灯效果

实现信号灯效果可以通过 Vue 的动态绑定和条件渲染功能完成。以下是一个完整的实现示例:

组件模板部分

<template>
  <div class="traffic-light">
    <div 
      class="light red" 
      :class="{ active: currentLight === 'red' }"
    ></div>
    <div 
      class="light yellow" 
      :class="{ active: currentLight === 'yellow' }"
    ></div>
    <div 
      class="light green" 
      :class="{ active: currentLight === 'green' }"
    ></div>
  </div>
</template>

组件脚本部分

<script>
export default {
  data() {
    return {
      currentLight: 'red',
      lightOrder: ['red', 'yellow', 'green', 'yellow'],
      currentIndex: 0,
      interval: null
    }
  },
  mounted() {
    this.startLightCycle()
  },
  beforeDestroy() {
    clearInterval(this.interval)
  },
  methods: {
    startLightCycle() {
      this.interval = setInterval(() => {
        this.currentIndex = (this.currentIndex + 1) % this.lightOrder.length
        this.currentLight = this.lightOrder[this.currentIndex]
      }, 2000)
    }
  }
}
</script>

样式部分

<style scoped>
.traffic-light {
  width: 100px;
  background: #333;
  border-radius: 10px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.light {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin: 10px 0;
  opacity: 0.3;
}

.light.red {
  background: red;
}

.light.yellow {
  background: yellow;
}

.light.green {
  background: green;
}

.light.active {
  opacity: 1;
  box-shadow: 0 0 20px 5px rgba(255, 255, 255, 0.5);
}
</style>

实现说明

  1. 数据驱动视图:使用 Vue 的响应式数据绑定功能,通过改变 currentLight 的值来控制哪个信号灯亮起。

  2. 定时切换:在组件挂载时启动定时器,按照预设的顺序循环切换信号灯状态。

  3. 样式控制:通过 CSS 类绑定实现信号灯的激活状态效果,使用透明度变化和阴影效果增强视觉表现。

  4. 生命周期管理:在组件销毁前清除定时器,避免内存泄漏。

扩展功能

如果需要更精确的控制,可以添加以下功能:

vue实现信号灯

methods: {
  changeLightDuration(duration) {
    clearInterval(this.interval)
    this.interval = setInterval(() => {
      this.currentIndex = (this.currentIndex + 1) % this.lightOrder.length
      this.currentLight = this.lightOrder[this.currentIndex]
    }, duration)
  }
}

这样可以通过调用 changeLightDuration 方法动态调整信号灯切换的时间间隔。

标签: 信号灯vue
分享给朋友:

相关文章

vue实现一个系统

vue实现一个系统

Vue 系统实现步骤 项目初始化与配置 使用 Vue CLI 或 Vite 创建项目: npm init vue@latest my-system 选择需要的配置(Router、Pinia 等)。…

vue实现$.extend

vue实现$.extend

Vue 实现类似 jQuery 的 $.extend 功能 在 Vue 中实现类似 jQuery 的 $.extend 功能,可以通过多种方式完成。$.extend 主要用于合并多个对象的属性,Vue…

vue实现token

vue实现token

Vue 中实现 Token 认证的方法 在 Vue 中实现 Token 认证通常涉及前端与后端的交互,包括 Token 的获取、存储、发送和刷新等操作。以下是具体实现步骤: 获取 Token 用户登…

vue实现addclass

vue实现addclass

Vue 实现动态添加 class 的方法 在 Vue 中动态添加 class 可以通过多种方式实现,以下是常见的几种方法: 使用对象语法 通过绑定一个对象到 :class,可以动态切换 class…

vue实现白板

vue实现白板

Vue实现白板功能 使用Vue实现白板功能可以通过HTML5的Canvas API结合Vue的响应式特性来完成。以下是实现白板功能的关键步骤: 安装依赖 在Vue项目中安装必要的依赖,如vue-dr…

vue实现 页面

vue实现 页面

Vue 实现页面的核心方法 创建 Vue 项目 使用 Vue CLI 或 Vite 快速初始化项目。Vue CLI 是官方脚手架工具,适合传统项目;Vite 提供更快的现代构建体验。 npm cre…