vue2实现抽奖
Vue2 抽奖功能实现
数据准备与初始化
在Vue实例的data中定义奖品列表和抽奖状态
data() {
return {
prizes: [
{ id: 1, name: '一等奖' },
{ id: 2, name: '二等奖' },
{ id: 3, name: '三等奖' },
{ id: 4, name: '参与奖' }
],
currentIndex: -1,
isRolling: false,
rollSpeed: 100,
result: null
}
}
抽奖动画实现
使用定时器实现转盘效果,通过不断改变currentIndex来高亮不同奖品

methods: {
startRoll() {
if (this.isRolling) return
this.isRolling = true
this.result = null
let rollCount = 0
const totalRolls = 30 + Math.floor(Math.random() * 20)
const roll = () => {
rollCount++
this.currentIndex = (this.currentIndex + 1) % this.prizes.length
if (rollCount < totalRolls) {
setTimeout(roll, this.rollSpeed)
} else {
this.stopRoll()
}
// 逐渐减速
if (rollCount > totalRolls * 0.7) {
this.rollSpeed += 20
}
}
roll()
}
}
停止抽奖逻辑
确定最终获奖结果并重置状态
methods: {
stopRoll() {
this.isRolling = false
this.rollSpeed = 100
// 随机确定获奖结果
this.result = this.prizes[Math.floor(Math.random() * this.prizes.length)]
// 高亮显示获奖项
this.currentIndex = this.prizes.findIndex(
item => item.id === this.result.id
)
}
}
模板部分
使用v-for渲染奖品列表,通过动态class实现高亮效果

<div class="lottery-container">
<div
v-for="(prize, index) in prizes"
:key="prize.id"
:class="['prize-item', { active: currentIndex === index }]"
>
{{ prize.name }}
</div>
<button @click="startRoll" :disabled="isRolling">
{{ isRolling ? '抽奖中...' : '开始抽奖' }}
</button>
<div v-if="result" class="result">
恭喜获得: {{ result.name }}
</div>
</div>
样式设计
添加基础样式和动画效果
.lottery-container {
display: flex;
flex-wrap: wrap;
max-width: 400px;
margin: 0 auto;
}
.prize-item {
width: 45%;
margin: 2.5%;
padding: 20px;
text-align: center;
background: #f0f0f0;
border-radius: 8px;
transition: all 0.3s;
}
.prize-item.active {
background: #ffeb3b;
transform: scale(1.05);
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}
button {
margin: 20px auto;
padding: 10px 20px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:disabled {
background: #cccccc;
}
进阶优化
可考虑添加以下增强功能:
- 增加音效(开始/停止音效)
- 实现真实转盘UI而非列表布局
- 添加中奖概率控制(不同奖项不同概率)
- 增加抽奖次数限制功能
- 使用transition-group实现更流畅的动画效果






