vue2实现抽奖
Vue2 实现抽奖功能
抽奖组件结构
在 Vue2 中实现抽奖功能通常需要以下核心部分:

- 奖品列表数据
- 抽奖动画效果
- 抽奖逻辑(随机选择奖品)
- 交互控制(开始/停止按钮)
奖品数据定义
在组件的 data 中定义奖品列表:

data() {
return {
prizes: [
{ id: 1, name: '一等奖', color: '#ff0000' },
{ id: 2, name: '二等奖', color: '#00ff00' },
{ id: 3, name: '三等奖', color: '#0000ff' },
// 更多奖品...
],
currentIndex: 0,
isRolling: false,
result: null
}
}
抽奖动画实现
使用 CSS 过渡效果创建旋转动画:
<template>
<div class="lottery-container">
<div class="prize-wheel" :style="{ transform: `rotate(${rotation}deg)` }">
<div
v-for="(prize, index) in prizes"
:key="prize.id"
class="prize-item"
:style="{ backgroundColor: prize.color, transform: `rotate(${index * angle}deg)` }"
>
{{ prize.name }}
</div>
</div>
<button @click="startLottery" :disabled="isRolling">
{{ isRolling ? '抽奖中...' : '开始抽奖' }}
</button>
</div>
</template>
抽奖逻辑实现
methods: {
startLottery() {
if (this.isRolling) return;
this.isRolling = true;
this.result = null;
// 动画持续时间
const duration = 3000;
// 旋转圈数
const circles = 5;
// 随机选择奖品
const prizeIndex = Math.floor(Math.random() * this.prizes.length);
const targetAngle = 360 - (prizeIndex * (360 / this.prizes.length));
// 总旋转角度 = 圈数*360 + 目标角度
const totalRotation = circles * 360 + targetAngle;
// 使用 CSS transition 实现动画
this.rotation = totalRotation;
// 动画结束后处理结果
setTimeout(() => {
this.isRolling = false;
this.result = this.prizes[prizeIndex];
alert(`恭喜获得: ${this.result.name}`);
}, duration);
}
}
CSS 样式
.lottery-container {
position: relative;
width: 300px;
height: 300px;
margin: 0 auto;
}
.prize-wheel {
width: 100%;
height: 100%;
border-radius: 50%;
position: relative;
transition: transform 3s cubic-bezier(0.17, 0.67, 0.12, 0.99);
transform: rotate(0deg);
}
.prize-item {
position: absolute;
width: 50%;
height: 50%;
left: 0;
top: 0;
transform-origin: right bottom;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
}
进阶优化
- 添加音效增强体验
- 实现减速动画效果
- 添加中奖概率控制
- 支持多种抽奖模式(九宫格、大转盘等)
概率控制实现
如果需要不同奖品有不同中奖概率:
data() {
return {
prizes: [
{ id: 1, name: '一等奖', color: '#ff0000', probability: 0.1 },
{ id: 2, name: '二等奖', color: '#00ff00', probability: 0.3 },
{ id: 3, name: '三等奖', color: '#0000ff', probability: 0.6 }
]
}
}
methods: {
getRandomPrize() {
const random = Math.random();
let sum = 0;
for (let i = 0; i < this.prizes.length; i++) {
sum += this.prizes[i].probability;
if (random <= sum) {
return i;
}
}
return this.prizes.length - 1;
}
}
这个实现提供了基本的抽奖功能,可以根据具体需求进一步扩展和完善。






