vue 实现闪烁
Vue 实现闪烁效果的方法
方法一:使用 CSS 动画
在 Vue 组件中定义一个闪烁的 CSS 动画,通过绑定 class 或 style 来控制元素的闪烁效果。
<template>
<div :class="{ 'blink': isBlinking }">闪烁的文字</div>
</template>
<script>
export default {
data() {
return {
isBlinking: true
}
}
}
</script>
<style>
.blink {
animation: blink 1s infinite;
}
@keyframes blink {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
</style>
方法二:使用 setInterval 控制
通过 JavaScript 的 setInterval 方法动态改变元素的样式或 class,实现闪烁效果。
<template>
<div :style="{ opacity: currentOpacity }">闪烁的文字</div>
</template>
<script>
export default {
data() {
return {
currentOpacity: 1,
interval: null
}
},
mounted() {
this.interval = setInterval(() => {
this.currentOpacity = this.currentOpacity === 1 ? 0 : 1
}, 500)
},
beforeDestroy() {
clearInterval(this.interval)
}
}
</script>
方法三:使用 Vue 过渡效果
利用 Vue 的内置过渡系统 <transition> 结合 CSS 实现闪烁效果。
<template>
<transition name="blink" mode="out-in">
<div v-if="show" key="text">闪烁的文字</div>
</transition>
</template>
<script>
export default {
data() {
return {
show: true
}
},
mounted() {
setInterval(() => {
this.show = !this.show
}, 500)
}
}
</script>
<style>
.blink-enter-active, .blink-leave-active {
transition: opacity .5s;
}
.blink-enter, .blink-leave-to {
opacity: 0;
}
</style>
方法四:使用第三方库
可以引入专门的动画库如 anime.js 或 GSAP 来实现更复杂的闪烁效果。
<template>
<div ref="blinkElement">闪烁的文字</div>
</template>
<script>
import anime from 'animejs'
export default {
mounted() {
anime({
targets: this.$refs.blinkElement,
opacity: [0, 1],
duration: 500,
loop: true,
direction: 'alternate'
})
}
}
</script>
注意事项
- 使用 CSS 动画性能更好,推荐优先考虑
- 使用 JavaScript 定时器时,注意在组件销毁前清除定时器
- 闪烁频率不宜过快,通常 0.5-1 秒的间隔比较合适
- 对于需要频繁闪烁的元素,考虑使用硬件加速(如 transform: translateZ(0))提升性能







