vue 实现跳动爱心
实现跳动爱心的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:

methods: {
toggleAnimation() {
this.isBeating = !this.isBeating;
}
}
<div
class="heart"
:class="{ animate: isBeating }"
@click="toggleAnimation"
></div>
以上方法提供了从简单到复杂的跳动爱心实现方式,可以根据项目需求选择合适的方案。CSS动画方案性能更优,适合复杂的动画效果;JavaScript控制方案则更灵活,便于与用户交互结合。






