当前位置:首页 > VUE

vue 实现闪烁

2026-01-12 18:19:38VUE

Vue 实现元素闪烁效果

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

vue 实现闪烁

<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 定时器动态改变样式实现更灵活的控制。

vue 实现闪烁

<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 定时器可以实现更复杂的逻辑控制
  • 记得在组件销毁时清除定时器防止内存泄漏
  • 可以根据需求调整闪烁频率和过渡效果

标签: vue
分享给朋友:

相关文章

vue实现点击

vue实现点击

实现点击事件的基本方法 在Vue中实现点击事件可以通过v-on指令或@简写方式绑定。以下是常见的点击事件绑定方法: <template> <button v-on:click=…

vue vnode实现

vue vnode实现

Vue VNode 实现原理 VNode(Virtual Node)是 Vue 的核心概念之一,用于描述真实 DOM 的轻量级虚拟表示。VNode 的实现涉及以下关键点: VNode 的基本结构 V…

vue compile 实现

vue compile 实现

Vue 编译实现原理 Vue 的编译过程将模板字符串转换为渲染函数,主要分为解析、优化和代码生成三个阶段。 解析阶段(Parse) 将模板字符串转换为抽象语法树(AST)。Vue 使用正则表达式和有…

vue nexttick 实现

vue nexttick 实现

Vue nextTick 实现原理 Vue 的 nextTick 是一个用于在下次 DOM 更新循环结束之后执行延迟回调的方法。它主要用于确保在 DOM 更新完成后执行某些操作。 核心实现机制 ne…

vue 实现聊天

vue 实现聊天

使用 Vue 实现聊天功能 创建 Vue 项目并安装依赖 确保已安装 Vue CLI,通过以下命令创建新项目: vue create chat-app 进入项目目录后,安装必要的依赖(如 Socke…

实现vue message

实现vue message

实现 Vue 消息提示组件 创建 Message 组件 在 src/components 目录下创建 Message.vue 文件,内容如下: <template> <tran…