当前位置:首页 > VUE

vue 实现跳动爱心

2026-03-08 06:32:22VUE

实现跳动爱心的Vue组件

在Vue中实现跳动爱心效果可以通过CSS动画和动态绑定样式来实现。以下是具体实现方法:

基础HTML结构

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

CSS样式部分

.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.3s 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;
}

Vue组件逻辑

<script>
export default {
  data() {
    return {
      scale: 1,
      isBeating: false
    }
  },
  methods: {
    animateHeart() {
      if (this.isBeating) return;

      this.isBeating = true;
      this.scale = 1.2;

      setTimeout(() => {
        this.scale = 1;
        setTimeout(() => {
          this.scale = 1.2;
          setTimeout(() => {
            this.scale = 1;
            this.isBeating = false;
          }, 300);
        }, 300);
      }, 300);
    }
  }
}
</script>

自动跳动效果

如需实现自动跳动效果,可以添加以下代码:

mounted() {
  setInterval(() => {
    this.animateHeart();
  }, 2000);
}

进阶动画效果

使用CSS keyframes实现更流畅的动画:

@keyframes heartbeat {
  0% { transform: scale(1) rotate(45deg); }
  25% { transform: scale(1.1) rotate(45deg); }
  40% { transform: scale(1) rotate(45deg); }
  60% { transform: scale(1.2) rotate(45deg); }
  100% { transform: scale(1) rotate(45deg); }
}

.heart.animate {
  animation: heartbeat 1s infinite;
}

然后在Vue中动态添加class:

vue 实现跳动爱心

methods: {
  toggleAnimation() {
    this.isBeating = !this.isBeating;
  }
}
<div 
  class="heart" 
  :class="{ animate: isBeating }"
  @click="toggleAnimation"
></div>

以上方法提供了从简单到复杂的跳动爱心实现方式,可以根据项目需求选择合适的方案。CSS动画方案性能更优,适合复杂的动画效果;JavaScript控制方案则更灵活,便于与用户交互结合。

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

相关文章

vue实现多个tab

vue实现多个tab

Vue 实现多个 Tab 的方法 使用动态组件切换 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现多个…

vue实现多用户登录

vue实现多用户登录

实现多用户登录的基本思路 在Vue中实现多用户登录通常需要结合后端API完成身份验证,并通过前端路由、状态管理(如Vuex或Pinia)和本地存储(如localStorage)来管理用户会话。以下是关…

vue实现选区

vue实现选区

Vue 实现选区的基本方法 在Vue中实现选区功能通常涉及DOM操作和事件处理。以下是几种常见的方法: 使用原生JavaScript的Selection API 通过window.getSelec…

vue 实现tabs

vue 实现tabs

Vue 实现 Tabs 组件的方法 使用动态组件和 v-for 在 Vue 中实现 Tabs 可以通过动态组件和 v-for 指令结合完成。定义一个 tabs 数组,包含每个标签的标题和对应的组件。…

vue实现granfana

vue实现granfana

Vue 实现类似 Grafana 的仪表盘 要在 Vue 中实现类似 Grafana 的仪表盘功能,需要结合数据可视化库、状态管理和 UI 组件。以下是关键步骤和推荐工具: 数据可视化库 使用 E…

vue实现suspense

vue实现suspense

Vue 3 中实现 Suspense Suspense 是 Vue 3 引入的一个内置组件,用于处理异步依赖的加载状态。它允许在等待异步组件或异步数据加载时显示一个后备内容(fallback),直到异…