vue实现信号灯
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>
实现说明
-
数据驱动视图:使用 Vue 的响应式数据绑定功能,通过改变
currentLight的值来控制哪个信号灯亮起。
-
定时切换:在组件挂载时启动定时器,按照预设的顺序循环切换信号灯状态。
-
样式控制:通过 CSS 类绑定实现信号灯的激活状态效果,使用透明度变化和阴影效果增强视觉表现。

-
生命周期管理:在组件销毁前清除定时器,避免内存泄漏。
扩展功能
如果需要更精确的控制,可以添加以下功能:
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 方法动态调整信号灯切换的时间间隔。






