vue抽奖代码实现
Vue 抽奖代码实现
基础抽奖组件结构
使用 Vue 的单文件组件(SFC)实现抽奖功能,核心包括奖品列表、抽奖动画和结果展示。
<template>
<div class="lottery-container">
<div class="prize-list">
<div
v-for="(prize, index) in prizes"
:key="index"
:class="{ active: activeIndex === index }"
>
{{ prize.name }}
</div>
</div>
<button @click="startLottery" :disabled="isRolling">开始抽奖</button>
<div v-if="result" class="result">恭喜获得:{{ result }}</div>
</div>
</template>
数据与状态定义
在 script 部分定义奖品数据和抽奖状态:
<script>
export default {
data() {
return {
prizes: [
{ name: '奖品1' },
{ name: '奖品2' },
{ name: '奖品3' },
{ name: '奖品4' },
{ name: '奖品5' },
{ name: '奖品6' }
],
activeIndex: -1,
isRolling: false,
result: null
}
}
}
</script>
抽奖动画逻辑
通过 setInterval 实现高亮切换动画,并通过随机数确定最终结果:

methods: {
startLottery() {
if (this.isRolling) return;
this.isRolling = true;
this.result = null;
let rollCount = 0;
const totalRolls = 30; // 动画总帧数
const speed = 100; // 动画速度(ms)
const timer = setInterval(() => {
rollCount++;
this.activeIndex = (this.activeIndex + 1) % this.prizes.length;
if (rollCount > totalRolls) {
clearInterval(timer);
this.isRolling = false;
this.result = this.prizes[this.activeIndex].name;
}
}, speed);
}
}
样式增强
添加基础样式提升视觉效果:
<style scoped>
.lottery-container {
text-align: center;
}
.prize-list {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin-bottom: 20px;
}
.prize-list div {
border: 1px solid #ddd;
padding: 20px;
transition: all 0.3s;
}
.prize-list div.active {
background-color: gold;
transform: scale(1.05);
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:disabled {
background-color: #cccccc;
}
</style>
进阶优化方向
概率控制 通过权重数组实现非均匀概率分布:

const weights = [10, 20, 30, 20, 15, 5]; // 各奖品权重
function getRandomPrizeIndex() {
const sum = weights.reduce((a, b) => a + b);
let random = Math.random() * sum;
for (let i = 0; i < weights.length; i++) {
if (random < weights[i]) return i;
random -= weights[i];
}
}
动画效果增强 使用 CSS 动画或第三方库(如 GSAP)实现更流畅的动画:
@keyframes flash {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
.active {
animation: flash 0.3s infinite;
}
后端集成 通过 API 获取奖品列表和提交结果:
async fetchPrizes() {
const res = await axios.get('/api/prizes');
this.prizes = res.data;
}
async submitResult() {
await axios.post('/api/record', { prize: this.result });
}






