vue实现发红包
实现思路
使用Vue实现发红包功能,主要涉及前端交互逻辑和动画效果。核心包括红包生成、点击动画、金额随机分配等。
基础组件结构
<template>
<div class="red-packet-container">
<button @click="showRedPacket">发红包</button>
<div v-if="isShow" class="red-packet" @click="openRedPacket">
<div class="packet-top"></div>
<div class="packet-body">{{ message }}</div>
<div class="packet-bottom"></div>
</div>
<div v-if="isOpen" class="money-show">
恭喜获得 {{ money }} 元!
</div>
</div>
</template>
数据与逻辑
<script>
export default {
data() {
return {
isShow: false,
isOpen: false,
message: '点击拆红包',
money: 0,
totalAmount: 100, // 红包总金额
count: 5 // 红包个数
}
},
methods: {
showRedPacket() {
this.isShow = true
this.isOpen = false
this.message = '点击拆红包'
},
openRedPacket() {
if (this.isOpen) return
// 随机金额算法(二倍均值法)
const max = this.totalAmount / this.count * 2
this.money = Math.random() * max
this.money = Math.floor(this.money * 100) / 100
this.isOpen = true
this.message = ''
this.totalAmount -= this.money
this.count--
}
}
}
</script>
样式设计
<style scoped>
.red-packet-container {
position: relative;
text-align: center;
}
.red-packet {
width: 200px;
height: 300px;
background: #E4393C;
margin: 20px auto;
position: relative;
cursor: pointer;
color: #FFD700;
font-weight: bold;
}
.packet-top {
width: 100%;
height: 40px;
background: #C81623;
border-radius: 100px 100px 0 0;
}
.packet-bottom {
width: 100%;
height: 20px;
background: #C81623;
border-radius: 0 0 100px 100px;
}
.money-show {
font-size: 24px;
color: #E4393C;
margin-top: 20px;
animation: bounce 0.5s;
}
@keyframes bounce {
0% { transform: scale(0.8); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
</style>
高级功能扩展
添加红包雨效果需要创建多个红包实例并控制它们的动画轨迹
// 在methods中添加
startRedPacketRain() {
const rainCount = 20
for (let i = 0; i < rainCount; i++) {
setTimeout(() => {
this.createFallingPacket()
}, i * 300)
}
},
createFallingPacket() {
const packet = document.createElement('div')
packet.className = 'falling-packet'
packet.style.left = `${Math.random() * window.innerWidth}px`
document.body.appendChild(packet)
const animation = packet.animate(
[
{ top: '-100px', opacity: 0 },
{ top: `${window.innerHeight}px`, opacity: 1 }
],
{ duration: 2000 }
)
animation.onfinish = () => {
packet.remove()
}
}
注意事项
- 金额分配算法应根据业务需求调整,常见有随机分配和定额分配
- 移动端需要添加touch事件支持
- 实际项目需要与后端API对接完成发红包和记录功能
- 性能优化:大量红包动画时应使用requestAnimationFrame







