Andy's blog

If you always do what you've always done, you'll always get what you've always got.

0%

Vue出一個樂透選取器

練習範本連結
Demo作品
延伸閱讀:取出不重複數字–使用ES6 set


步驟:
Step1.利用v-for range選染出49個陣列
Step2.點選號碼(確認是否點擊到)

1
<div v-for="n in 49" @click="selectNum(n)"> {{n}}</div>
1
2
3
4
5
methods: {
selectNum(n){
console.log(n)
}
},

Step3.接著就可以將選中號碼印出對應顏色

1
:class="{ selected: choose.includes(n) }"

Step4.挑選不重複六個號碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
methods: {
selectNum(n) {
// 不加入重複的陣列資料
if (this.choose.includes(n)) {
this.choose = this.choose.filter(d => d !== n)
// console.log(this.choose)
}
// 挑選最多六個
else if (this.choose.length <6) {
this.choose.push(n)
}
}
},

Step5
隨機開獎六個數字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
getLotteryNum() {
if (this.choose.length < 6) {
alert('請挑選六個數字')
}
else{
// 需要挑選不重複六組號碼
var ary = [];
for (let i = 1; i < 50; i++) {
ary.push(i)
}
// 洗牌
var random = ary.sort(() => Math.random() - 0.5)
// console.log(random)

// 挑選六個號碼
this.lotteryNum = random.slice(0, 6)
console.log(this.lotteryNum)
}
},

Step6.
印出開講顏色(紅色)

1
2
3
4
5
6
     <div v-for="n in 49" @click="selectNum(n)" 
:class="{
selected: choose.includes(n),
highlight: lotteryNum.includes(n),
}"> {{n}}
</div>