vue实现呼吸灯
使用 CSS 动画实现呼吸灯效果
在 Vue 中实现呼吸灯效果可以通过 CSS 动画结合动态样式绑定完成。以下是具体实现方法:
-
定义呼吸灯动画样式 在组件的
<style>部分或全局 CSS 中定义关键帧动画:@keyframes breathe { 0% { opacity: 0.4; } 50% { opacity: 1; } 100% { opacity: 0.4; } } -
绑定动画到元素 通过
:style或:class绑定动画到目标元素:<template> <div class="breathing-light" :style="lightStyle"></div> </template> -
控制动画参数 在 Vue 的
data或computed中定义动画参数:
export default { data() { return { duration: 2, // 动画周期(秒) color: '#00ff00' // 呼吸灯颜色 } }, computed: { lightStyle() { return { animation: `breathe ${this.duration}s infinite ease-in-out`, backgroundColor: this.color } } } }
使用 JavaScript 动态控制
需要更精细控制时,可以通过 JavaScript 定时器实现:
-
模板定义
<div class="light" :style="{ opacity: currentOpacity }"></div> -
实现呼吸逻辑

export default { data() { return { currentOpacity: 0.4, direction: 1, speed: 0.02 } }, mounted() { this.animate() }, methods: { animate() { requestAnimationFrame(() => { this.currentOpacity += this.speed * this.direction if (this.currentOpacity >= 1) this.direction = -1 if (this.currentOpacity <= 0.4) this.direction = 1 this.animate() }) } } }
封装为可复用组件
将呼吸灯功能封装为组件便于复用:
-
组件定义
<!-- BreathingLight.vue --> <template> <div class="breathing-light" :style="computedStyle"></div> </template> <script> export default { props: { color: { type: String, default: '#00ff00' }, duration: { type: Number, default: 2 } }, computed: { computedStyle() { return { animation: `breathe ${this.duration}s infinite ease-in-out`, backgroundColor: this.color } } } } </script> <style> @keyframes breathe { 0% { opacity: 0.4; } 50% { opacity: 1; } 100% { opacity: 0.4; } } .breathing-light { width: 20px; height: 20px; border-radius: 50%; } </style> -
使用组件
<BreathingLight color="#ff0000" :duration="3" />
性能优化建议
- 优先使用 CSS 动画而非 JavaScript 实现
- 对多个呼吸灯实例使用相同的动画名称
- 考虑使用
will-change: opacity提升渲染性能 - 移除组件时清除动画相关资源
以上方法可根据实际需求选择或组合使用,CSS 动画方案性能更优,而 JavaScript 方案则提供更多控制灵活性。






