vue 实现跳动爱心
Vue 实现跳动爱心效果
可以通过 CSS 动画结合 Vue 的动态绑定实现爱心跳动效果。以下是具体实现方法:
基础爱心形状
使用 CSS 绘制爱心形状,可以通过伪元素创建:
<template>
<div class="heart-container">
<div class="heart" :style="heartStyle"></div>
</div>
</template>
<style>
.heart {
width: 100px;
height: 100px;
background-color: red;
position: relative;
transform: rotate(45deg);
}
.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>
添加跳动动画
通过 CSS 动画实现缩放效果:
@keyframes heartbeat {
0% {
transform: rotate(45deg) scale(1);
}
25% {
transform: rotate(45deg) scale(1.1);
}
50% {
transform: rotate(45deg) scale(1);
}
75% {
transform: rotate(45deg) scale(1.1);
}
100% {
transform: rotate(45deg) scale(1);
}
}
.heart {
animation: heartbeat 1.5s infinite;
}
Vue 动态控制
添加响应式数据控制动画状态:
<script>
export default {
data() {
return {
isBeating: true
}
},
computed: {
heartStyle() {
return {
animation: this.isBeating ? 'heartbeat 1.5s infinite' : 'none'
}
}
},
methods: {
toggleHeartbeat() {
this.isBeating = !this.isBeating
}
}
}
</script>
点击交互效果
添加点击事件使爱心跳动更明显:
<template>
<div class="heart-container" @click="pulseHeart">
<div class="heart" :style="heartStyle"></div>
</div>
</template>
<script>
export default {
methods: {
pulseHeart() {
this.isBeating = false
setTimeout(() => {
this.isBeating = true
}, 100)
}
}
}
</script>
进阶效果
可以添加随机颜色和位置变化:
data() {
return {
colors: ['#ff0000', '#ff69b4', '#ff1493', '#ff00ff'],
currentColor: '#ff0000'
}
},
methods: {
changeColor() {
const randomIndex = Math.floor(Math.random() * this.colors.length)
this.currentColor = this.colors[randomIndex]
}
}
然后在样式中使用动态绑定:
<div class="heart"
:style="{
'background-color': currentColor,
'animation': isBeating ? 'heartbeat 1.5s infinite' : 'none'
}">
</div>
性能优化
对于多个爱心的情况,使用 Vue 的列表渲染:

<template>
<div>
<div
v-for="(heart, index) in hearts"
:key="index"
class="heart-item"
@click="pulseHeart(index)"
>
<div class="heart" :style="getHeartStyle(index)"></div>
</div>
</div>
</template>
以上方法结合了 Vue 的响应式特性和 CSS 动画,可以创建出流畅的爱心跳动效果。






