vue 实现闪烁
Vue 实现元素闪烁效果
方法一:使用 CSS 动画 通过 Vue 绑定 class 或 style 来触发 CSS 动画实现闪烁效果。

<template>
<div :class="{ 'blink': isBlinking }">闪烁内容</div>
<button @click="toggleBlink">切换闪烁</button>
</template>
<script>
export default {
data() {
return {
isBlinking: false
}
},
methods: {
toggleBlink() {
this.isBlinking = !this.isBlinking
}
}
}
</script>
<style>
.blink {
animation: blink 1s infinite;
}
@keyframes blink {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
</style>
方法二:使用 setInterval 通过 JavaScript 定时器动态改变样式实现更灵活的控制。

<template>
<div :style="{ opacity: currentOpacity }">动态闪烁内容</div>
<button @click="startBlink">开始闪烁</button>
<button @click="stopBlink">停止闪烁</button>
</template>
<script>
export default {
data() {
return {
currentOpacity: 1,
blinkInterval: null
}
},
methods: {
startBlink() {
this.blinkInterval = setInterval(() => {
this.currentOpacity = this.currentOpacity === 1 ? 0 : 1
}, 500)
},
stopBlink() {
clearInterval(this.blinkInterval)
this.currentOpacity = 1
}
},
beforeDestroy() {
clearInterval(this.blinkInterval)
}
}
</script>
方法三:使用 Vue 过渡 结合 Vue 的 transition 组件实现平滑的闪烁效果。
<template>
<transition name="blink" mode="out-in">
<div v-if="show" key="content">过渡闪烁内容</div>
</transition>
<button @click="toggleShow">切换显示</button>
</template>
<script>
export default {
data() {
return {
show: true,
toggleTimer: null
}
},
methods: {
toggleShow() {
this.toggleTimer = setInterval(() => {
this.show = !this.show
}, 1000)
}
},
beforeDestroy() {
clearInterval(this.toggleTimer)
}
}
</script>
<style>
.blink-enter-active, .blink-leave-active {
transition: opacity 0.5s;
}
.blink-enter, .blink-leave-to {
opacity: 0;
}
</style>
注意事项
- 使用 CSS 动画性能更好,适合简单的闪烁效果
- JavaScript 定时器可以实现更复杂的逻辑控制
- 记得在组件销毁时清除定时器防止内存泄漏
- 可以根据需求调整闪烁频率和过渡效果






