vue3实现抽奖
Vue3 实现抽奖功能
抽奖功能的实现通常包括以下几个关键部分:奖品列表、抽奖动画、随机选择和中奖逻辑。以下是基于 Vue3 的实现方法。
奖品列表配置
在 Vue3 的 setup 中定义奖品列表和相关状态:

import { ref } from 'vue';
const prizes = ref([
{ id: 1, name: '一等奖', probability: 0.1 },
{ id: 2, name: '二等奖', probability: 0.2 },
{ id: 3, name: '三等奖', probability: 0.3 },
{ id: 4, name: '谢谢参与', probability: 0.4 }
]);
const currentPrize = ref(null);
const isRolling = ref(false);
抽奖动画实现
使用 CSS 动画或 JavaScript 定时器实现抽奖的滚动效果。以下是基于定时器的实现:
const rollAnimation = () => {
let rollCount = 0;
const maxRolls = 20; // 滚动次数
const interval = setInterval(() => {
rollCount++;
const randomIndex = Math.floor(Math.random() * prizes.value.length);
currentPrize.value = prizes.value[randomIndex];
if (rollCount >= maxRolls) {
clearInterval(interval);
isRolling.value = false;
determineWinner(); // 最终确定中奖结果
}
}, 100); // 每100毫秒切换一次显示
};
中奖逻辑
根据奖品的概率权重随机选择最终中奖结果:

const determineWinner = () => {
const random = Math.random();
let cumulativeProbability = 0;
for (const prize of prizes.value) {
cumulativeProbability += prize.probability;
if (random <= cumulativeProbability) {
currentPrize.value = prize;
break;
}
}
};
触发抽奖
在模板中添加抽奖按钮并绑定事件:
<template>
<div class="lottery-container">
<div class="prize-display">{{ currentPrize?.name || '准备抽奖' }}</div>
<button @click="startLottery" :disabled="isRolling">
{{ isRolling ? '抽奖中...' : '开始抽奖' }}
</button>
</div>
</template>
<script setup>
const startLottery = () => {
if (isRolling.value) return;
isRolling.value = true;
rollAnimation();
};
</script>
样式优化
添加基本样式增强视觉效果:
.lottery-container {
text-align: center;
margin-top: 50px;
}
.prize-display {
font-size: 24px;
margin-bottom: 20px;
height: 30px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
}
button:disabled {
background-color: #cccccc;
}
注意事项
- 概率权重应总和为1,否则需要归一化处理
- 抽奖动画时间不宜过短或过长,通常控制在2-3秒
- 移动端适配可能需要调整字体大小和按钮尺寸
- 实际项目中可能需要添加API调用记录中奖结果
以上实现可以根据实际需求扩展,如添加音效、更复杂的动画效果或多轮抽奖逻辑。






