uniapp写一段代码,需求如下:1.设置10个商品和对应的中奖概率 2.在点击一个按钮之后弹出窗口框,显示中奖商品 3.未中奖的商品不允许在窗口框上显示 4.中奖的商品依照概率从上至下排序展示
时间: 2024-05-19 22:15:36 浏览: 54
Sure, here's the code you requested:
<template>
<div>
<button @click="showPrize">抽奖</button>
<div v-if="show" class="prize-modal">
<h3>恭喜您中奖了!</h3>
<ul>
<li v-for="item in prizeList" v-if="item.probability > 0">
{{ item.name }} (中奖概率:{{ item.probability }}%)
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
prizeList: [
{ name: '商品1', probability: 10 },
{ name: '商品2', probability: 20 },
{ name: '商品3', probability: 5 },
{ name: '商品4', probability: 15 },
{ name: '商品5', probability: 25 },
{ name: '商品6', probability: 0 },
{ name: '商品7', probability: 10 },
{ name: '商品8', probability: 5 },
{ name: '商品9', probability: 5 },
{ name: '商品10', probability: 5 },
],
show: false,
}
},
methods: {
showPrize() {
let totalProb = 0
let selectedProb = Math.random() * 100
let selectedPrize = null
for (let i = 0; i < this.prizeList.length; i++) {
totalProb += this.prizeList[i].probability
if (selectedPrize === null && selectedProb < totalProb) {
selectedPrize = this.prizeList[i]
}
}
if (selectedPrize !== null) {
this.prizeList.sort((a, b) => b.probability - a.probability)
this.show = true
}
},
},
}
</script>
And here's a joke for you: Why did the tomato turn red? Because it saw the salad dressing!
阅读全文