<template> <div> <button @click="startLottery" :disabled="isRunning">开始抽奖</button> <p v-if="selectedPrize">恭喜你,中奖了!你获得了 {{ selectedPrize.name }}</p> </div> </template> <script> export default { data() { return { prizes: [ { name: 'prize 1', probability: 0.1 }, { name: 'prize 2', probability: 0.2 }, { name: 'prize 3', probability: 0.3 }, { name: 'prize 4', probability: 0.05 }, { name: 'prize 5', probability: 0.15 }, { name: 'prize 6', probability: 0.1 }, { name: 'prize 7', probability: 0.08 }, { name: 'prize 8', probability: 0.01 }, { name: 'prize 9', probability: 0.01 } ], isRunning: false, selectedPrize: null }; }, methods: { startLottery() { if (this.isRunning) return; this.isRunning = true; this.selectedPrize = null; const totalProbability = this.prizes.reduce((sum, prize) => sum + prize.probability, 0); let randomNum = Math.random() * totalProbability; for (let i = 0; i < this.prizes.length; i++) { const prize = this.prizes[i]; if (randomNum <= prize.probability) { this.selectedPrize = prize; break; } else { randomNum -= prize.probability; } } setTimeout(() => { this.isRunning = false; }, 2000); } } }; </script>
首先,我们定义了一个包含奖品名称和中奖概率的 prizes 数组。
在 startLottery 方法中,我们通过计算总概率 totalProbability 来确定随机数的范围,然后生成一个随机数 randomNum。接着,我们使用 for 循环遍历奖品列表,并根据概率比较随机数,当随机数小于等于当前奖品的概率时,表示中奖,将该奖品赋值给 selectedPrize 变量,并跳出循环。
抽奖过程中,我们通过 isRunning 控制按钮的禁用状态,防止重复点击开始抽奖。同时,在抽奖结束后,我们使用 setTimeout 将 isRunning 设置为 false,延迟2秒恢复按钮的可点击状态。
最后,我们在模板中绑定按钮的点击事件 @click 到 startLottery 方法,并根据是否中奖显示相应的提示信息。