vue 实现跳动爱心
实现跳动爱心的步骤
使用CSS动画和Vue动态绑定
在Vue中创建一个跳动爱心,可以通过CSS动画结合Vue的动态绑定实现。定义一个爱心的形状,使用CSS关键帧动画控制缩放效果。

<template>
<div class="heart" :style="{ transform: `scale(${scale})` }"></div>
</template>
<script>
export default {
data() {
return {
scale: 1,
animationInterval: null
};
},
mounted() {
this.animationInterval = setInterval(() => {
this.scale = this.scale === 1 ? 1.2 : 1;
}, 500);
},
beforeDestroy() {
clearInterval(this.animationInterval);
}
};
</script>
<style>
.heart {
width: 50px;
height: 50px;
background-color: red;
position: relative;
transform: rotate(45deg);
margin: 100px auto;
transition: transform 0.3s ease;
}
.heart:before,
.heart:after {
content: "";
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
position: absolute;
}
.heart:before {
top: -25px;
left: 0;
}
.heart:after {
top: 0;
left: -25px;
}
</style>
使用第三方动画库
如果需要更复杂的动画效果,可以引入anime.js或GSAP等动画库。以下示例使用anime.js实现心跳效果。

<template>
<div class="heart" ref="heart"></div>
</template>
<script>
import anime from 'animejs';
export default {
mounted() {
anime({
targets: this.$refs.heart,
scale: [1, 1.3, 1],
duration: 800,
loop: true,
easing: 'easeInOutSine'
});
}
};
</script>
<style>
.heart {
width: 50px;
height: 50px;
background-color: red;
position: relative;
transform: rotate(45deg);
margin: 100px auto;
}
.heart:before,
.heart:after {
content: "";
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
position: absolute;
}
.heart:before {
top: -25px;
left: 0;
}
.heart:after {
top: 0;
left: -25px;
}
</style>
使用SVG和Vue动态属性
SVG路径可以更灵活地绘制爱心形状,通过动态修改属性实现动画效果。
<template>
<svg width="100" height="100" viewBox="0 0 100 100">
<path
:d="pathData"
fill="red"
:transform="`scale(${scale})`"
transform-origin="50 50"
/>
</svg>
</template>
<script>
export default {
data() {
return {
pathData: "M50 30 L20 10 A20 20 0 0 0 50 50 A20 20 0 0 0 80 10 Z",
scale: 1
};
},
mounted() {
setInterval(() => {
this.scale = this.scale === 1 ? 1.2 : 1;
}, 500);
}
};
</script>
结合Vue过渡效果
Vue的<transition>组件可以用于控制爱心的显隐和跳动效果。
<template>
<transition name="pulse">
<div class="heart"></div>
</transition>
</template>
<style>
.heart {
width: 50px;
height: 50px;
background-color: red;
position: relative;
transform: rotate(45deg);
margin: 100px auto;
}
.heart:before,
.heart:after {
content: "";
width: 50px;
height: 50px;
background-color: red;
border-radius: 50%;
position: absolute;
}
.heart:before {
top: -25px;
left: 0;
}
.heart:after {
top: 0;
left: -25px;
}
.pulse-enter-active, .pulse-leave-active {
transition: transform 0.5s;
}
.pulse-enter, .pulse-leave-to {
transform: rotate(45deg) scale(1.2);
}
</style>
以上方法均能实现爱心的跳动效果,选择适合项目需求的方式即可。CSS动画适合简单场景,第三方库适合复杂动画,SVG适合需要精确控制路径的场景。






