vue实现呼吸灯
Vue 实现呼吸灯效果
呼吸灯效果可以通过 CSS 动画结合 Vue 的动态样式绑定实现。以下是两种常见方法:

使用 CSS 动画和 Vue 数据绑定
定义 CSS 关键帧动画:

@keyframes breathe {
0% { opacity: 0.4; }
50% { opacity: 1; }
100% { opacity: 0.4; }
}
.breathe-effect {
animation: breathe 3s infinite;
}
在 Vue 组件中应用:
<template>
<div class="breathe-effect" :style="{ 'animation-duration': duration + 's' }">
<!-- 你的内容 -->
</div>
</template>
<script>
export default {
data() {
return {
duration: 3 // 可动态调整呼吸周期
}
}
}
</script>
使用 Vue 过渡和动态样式
通过计算属性动态控制透明度:
<template>
<div
class="breathing-element"
:style="{ opacity: currentOpacity }"
></div>
</template>
<script>
export default {
data() {
return {
minOpacity: 0.4,
maxOpacity: 1,
speed: 0.01,
currentOpacity: 0.4,
increasing: true
}
},
mounted() {
this.animateBreath()
},
methods: {
animateBreath() {
if (this.increasing) {
this.currentOpacity += this.speed
if (this.currentOpacity >= this.maxOpacity) {
this.increasing = false
}
} else {
this.currentOpacity -= this.speed
if (this.currentOpacity <= this.minOpacity) {
this.increasing = true
}
}
requestAnimationFrame(this.animateBreath)
}
}
}
</script>
<style>
.breathing-element {
width: 100px;
height: 100px;
background-color: #42b983;
transition: opacity 0.1s linear;
}
</style>
注意事项
- 性能优化:CSS 动画通常比 JavaScript 实现的动画性能更好
- 移动端适配:可以添加
-webkit-前缀确保兼容性 - 自定义参数:通过 props 接收呼吸周期、颜色等参数使组件更灵活






