vue实现红包雨
Vue 实现红包雨功能
红包雨是一种常见的互动效果,通常在节日或促销活动中使用。以下是使用 Vue 实现红包雨功能的详细方法。
准备工作
确保项目已安装 Vue 2 或 Vue 3,并准备好相关依赖。如果使用 Vue 3,推荐使用 Composition API。
创建红包组件
创建一个红包组件 RedPacket.vue,用于渲染单个红包的样式和行为。
<template>
<div
class="red-packet"
:style="{
left: `${position.x}px`,
top: `${position.y}px`,
transform: `rotate(${rotation}deg)`,
animationDuration: `${duration}s`
}"
@click="onClick"
>
<div class="content">{{ amount }}</div>
</div>
</template>
<script>
export default {
props: {
position: {
type: Object,
required: true
},
duration: {
type: Number,
default: 5
},
amount: {
type: Number,
default: 0
}
},
data() {
return {
rotation: Math.random() * 30 - 15 // 随机旋转角度
}
},
methods: {
onClick() {
this.$emit('click', this.amount)
}
}
}
</script>
<style scoped>
.red-packet {
position: absolute;
width: 60px;
height: 80px;
background-image: url('red-packet.png');
background-size: contain;
background-repeat: no-repeat;
cursor: pointer;
animation: fall linear;
}
@keyframes fall {
to {
transform: translateY(100vh);
}
}
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-weight: bold;
}
</style>
实现红包雨主逻辑
在父组件中控制红包的生成、动画和点击事件。

<template>
<div class="red-packet-rain">
<RedPacket
v-for="(packet, index) in packets"
:key="index"
:position="packet.position"
:duration="packet.duration"
:amount="packet.amount"
@click="handlePacketClick"
/>
</div>
</template>
<script>
import RedPacket from './RedPacket.vue'
export default {
components: { RedPacket },
data() {
return {
packets: [],
timer: null
}
},
mounted() {
this.startRain()
},
beforeUnmount() {
this.stopRain()
},
methods: {
startRain() {
this.timer = setInterval(() => {
this.createPacket()
}, 300) // 每300ms生成一个红包
},
stopRain() {
clearInterval(this.timer)
},
createPacket() {
const packet = {
position: {
x: Math.random() * window.innerWidth,
y: -100 // 从屏幕顶部外开始下落
},
duration: 3 + Math.random() * 5, // 下落时间3-8秒
amount: Math.floor(Math.random() * 100) + 1 // 随机金额1-100
}
this.packets.push(packet)
// 移除已经落下的红包
setTimeout(() => {
this.packets = this.packets.filter(p => p !== packet)
}, packet.duration * 1000)
},
handlePacketClick(amount) {
alert(`恭喜获得${amount}元红包!`)
}
}
}
</script>
<style scoped>
.red-packet-rain {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
}
</style>
优化与扩展
-
性能优化
对于大量红包,可以使用虚拟滚动或对象池技术复用 DOM 元素。 -
碰撞检测
添加简单的碰撞检测,避免红包重叠。 -
多种红包样式
通过随机选择不同的红包图片增加视觉效果。
-
音效
添加下落和点击音效增强体验。 -
移动端适配
确保在移动设备上也能正常显示和交互。
完整示例整合
将上述代码整合到一个完整的 Vue 项目中,并添加必要的资源文件(如红包图片)。运行项目即可看到红包雨效果。
通过以上方法,可以快速实现一个基本的红包雨功能,并根据需求进一步扩展和优化。






