当前位置:首页 > 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 的值来控制哪个信号灯亮起。

    vue实现信号灯

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

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

    vue实现信号灯

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

扩展功能

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

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 中实现文档导入功能通常涉及文件上传、解析和处理。以下是几种常见的方法: 使用原生文件输入和 FileReader 通过 HTML 的原生 <input…

vue实现发送值接受值

vue实现发送值接受值

Vue 实现父子组件传值 父组件向子组件传值(props) 父组件通过 v-bind 或简写 : 向子组件传递数据。子组件通过 props 接收数据。 父组件代码: <template&g…

vue 方法实现

vue 方法实现

在 Vue 中,方法的实现通常通过 methods 选项完成。以下是 Vue 方法实现的核心要点和示例: 基本方法定义 在 Vue 组件中定义方法时,需将函数声明放在 methods 对象内。这些…

vue实现过滤

vue实现过滤

Vue实现过滤的方法 在Vue中实现数据过滤可以通过多种方式完成,以下是几种常见的方法: 使用计算属性过滤 计算属性是Vue中处理数据过滤的理想选择,它们基于响应式依赖进行缓存,只有在相关依赖发生…

vue实现全景

vue实现全景

Vue 实现全景效果的方法 使用 Vue 实现全景效果通常需要结合第三方库或框架,以下是几种常见的方法: 使用 Three.js 和 Vue-Three.js Three.js 是一个强大的 3D…

vue实现返回

vue实现返回

返回按钮功能实现 在Vue中实现返回功能通常有两种方式:使用浏览器历史记录的history.back()或结合Vue Router进行编程式导航。以下是具体实现方法: 使用浏览器API met…