当前位置:首页 > VUE

vue 实现跳动爱心

2026-02-11 06:50:43VUE

实现跳动爱心的 Vue 组件

以下是使用 Vue 3 实现跳动爱心的代码示例,通过 CSS 动画和动态样式实现效果。

模板部分

<template>
  <div class="heart-container">
    <div 
      class="heart" 
      :style="{ transform: `scale(${scale})` }"
      @click="toggleBeat"
    ></div>
  </div>
</template>

脚本部分

vue 实现跳动爱心

<script>
import { ref } from 'vue';

export default {
  setup() {
    const scale = ref(1);
    const isBeating = ref(false);
    let beatInterval;

    const startBeat = () => {
      isBeating.value = true;
      let growing = true;
      beatInterval = setInterval(() => {
        if (growing) {
          scale.value += 0.05;
          if (scale.value >= 1.2) growing = false;
        } else {
          scale.value -= 0.05;
          if (scale.value <= 1) growing = true;
        }
      }, 100);
    };

    const stopBeat = () => {
      isBeating.value = false;
      clearInterval(beatInterval);
      scale.value = 1;
    };

    const toggleBeat = () => {
      isBeating.value ? stopBeat() : startBeat();
    };

    return { scale, toggleBeat };
  }
};
</script>

样式部分

<style scoped>
.heart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.heart {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  transform: rotate(45deg);
  cursor: pointer;
  transition: transform 0.1s ease;
}

.heart:before,
.heart:after {
  content: '';
  width: 100px;
  height: 100px;
  background-color: red;
  border-radius: 50%;
  position: absolute;
}

.heart:before {
  top: -50px;
  left: 0;
}

.heart:after {
  top: 0;
  left: -50px;
}
</style>

实现原理

  1. 爱心形状
    通过 CSS 创建正方形元素并旋转 45 度,配合两个伪元素形成圆形,组合成爱心形状。

    vue 实现跳动爱心

  2. 跳动动画
    使用 JavaScript 定时器动态修改 transform 的 scale 值,在 1 到 1.2 之间循环变化,模拟心跳效果。

  3. 交互控制
    点击爱心时触发 toggleBeat 方法,控制动画的启动和停止。

  4. 响应式样式
    通过 Vue 的 ref 响应式变量 scale 动态绑定样式,实现平滑的缩放效果。

扩展建议

  1. 添加更多动画效果如颜色渐变或位置移动
  2. 使用 CSS @keyframes 实现更复杂的动画序列
  3. 通过 props 接收自定义颜色和大小参数
  4. 添加音效增强交互体验

该组件可以直接在 Vue 项目中导入使用,或根据需求进一步调整动画参数和样式。

标签: 爱心vue
分享给朋友:

相关文章

vue实现生成二维码

vue实现生成二维码

使用qrcode.vue库生成二维码 安装qrcode.vue库: npm install qrcode.vue --save 在Vue组件中使用: <template> <…

vue实现语音

vue实现语音

Vue 实现语音功能的方法 使用 Web Speech API Vue 可以结合 Web Speech API 实现语音识别和合成功能。Web Speech API 包含 SpeechRecognit…

分页实现vue

分页实现vue

分页实现(Vue) 在Vue中实现分页功能通常需要结合前端分页逻辑和后端API支持。以下是两种常见的实现方式: 前端分页实现 适用于数据量较小的情况,直接在客户端完成分页逻辑。 <templ…

实现vue table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,支…

vue实现api

vue实现api

Vue 实现 API 调用 在 Vue 中调用 API 通常涉及使用 axios 或 fetch 发送 HTTP 请求,并结合 Vue 的响应式特性管理数据。以下是常见的实现方式: 安装 axios…