vue 实现抽奖
Vue 实现抽奖功能
抽奖功能通常包括奖品展示、抽奖动画、中奖结果展示等部分。以下是一个基于 Vue 的实现方案:
数据准备
data() {
return {
prizes: [
{ id: 1, name: '一等奖', color: '#ff0000' },
{ id: 2, name: '二等奖', color: '#00ff00' },
{ id: 3, name: '三等奖', color: '#0000ff' },
{ id: 4, name: '四等奖', color: '#ffff00' },
{ id: 5, name: '五等奖', color: '#ff00ff' },
{ id: 6, name: '六等奖', color: '#00ffff' }
],
currentIndex: 0,
isRolling: false,
result: null
}
}
抽奖动画实现
methods: {
startLottery() {
if (this.isRolling) return
this.isRolling = true
this.result = null
const roll = () => {
this.currentIndex = (this.currentIndex + 1) % this.prizes.length
}
const interval = setInterval(roll, 100)
setTimeout(() => {
clearInterval(interval)
const duration = 2000 + Math.random() * 3000
const slowRoll = () => {
roll()
if (Date.now() - startTime >= duration) {
clearInterval(slowInterval)
this.isRolling = false
this.result = this.prizes[this.currentIndex]
}
}
const startTime = Date.now()
const slowInterval = setInterval(slowRoll, 200)
}, 2000)
}
}
模板部分
<template>
<div class="lottery-container">
<div class="prize-wheel">
<div
v-for="(prize, index) in prizes"
:key="prize.id"
class="prize-item"
:class="{ active: currentIndex === index }"
:style="{ backgroundColor: prize.color }"
>
{{ prize.name }}
</div>
</div>
<button
@click="startLottery"
:disabled="isRolling"
class="lottery-btn"
>
{{ isRolling ? '抽奖中...' : '开始抽奖' }}
</button>
<div v-if="result" class="result">
恭喜获得: <span :style="{ color: result.color }">{{ result.name }}</span>
</div>
</div>
</template>
CSS 样式
.lottery-container {
text-align: center;
padding: 20px;
}
.prize-wheel {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 300px;
margin: 0 auto 20px;
position: relative;
}
.prize-item {
width: 100px;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ddd;
box-sizing: border-box;
transition: all 0.3s;
}
.prize-item.active {
transform: scale(1.1);
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
.lottery-btn {
padding: 10px 20px;
background: #409eff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.lottery-btn:disabled {
background: #a0cfff;
cursor: not-allowed;
}
.result {
margin-top: 20px;
font-size: 18px;
}
优化建议
- 可以添加音效增强用户体验
- 考虑添加奖品概率控制
- 增加动画缓动效果使停止更自然
- 支持多种抽奖模式(九宫格、转盘等)
- 添加抽奖次数限制功能
这个实现提供了基本的抽奖功能,可以根据实际需求进行调整和扩展。动画效果通过定时器实现,保证了抽奖过程的流畅性,同时加入了随机停止时间增加了趣味性。







