Vue_cli实现抽奖
<template>
<div class="test02">
<p>我是test02</p>
<div class="prize">
<ul>
<li v-for="(item, i) of mapList" :key="i" :class="{active: activeIndex === item.index}" @click="startLuck(item)">{{item.text}}</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data () {
return {
activeIndex: null, // 当前抽中的奖品
lucky: null, // 抽中的商品
// 奖品数据
list: [
{ id: 1, text: '奖品1' }, // 0
{ id: 2, text: '奖品2' }, // 1
{ id: 3, text: '奖品3' }, // 2
{ id: 4, text: '奖品4' }, // 3
{ id: 5, text: '奖品5' }, // 4
{ id: 6, text: '奖品6' }, // 5
{ id: 7, text: '奖品7' }, // 6
{ id: 8, text: '奖品8' } // 7
]
}
},
computed: {
mapList () {
// map 修改原素组返回新数组,但是原素组不受影响
const newList = this.list.map((item, index) => {
// 修改list数据的索引
switch (index) {
case 3:
return {
...this.list[7],
index: 7
}
case 4:
return {
...this.list[3],
index: 3
}
case 5:
return {
...this.list[6],
index: 6
}
case 6:
return {
...this.list[5],
index: 5
}
case 7:
return {
...this.list[4],
index: 4
}
default:
return {
...item,
index: index
}
}
})
// 将新数组newList截取前三个 + 自定义一个按钮 + newlist的后4个
return newList.slice(0, 4).concat({ id: 'btn', text: '开始抽奖' }).concat(newList.slice(4))
/*
return的数据
0: {id: 1, text: "奖品1", index: 0}
1: {id: 2, text: "奖品2", index: 1}
2: {id: 3, text: "奖品3", index: 2}
3: {id: 8, text: "奖品8", index: 7}
4: {id: "btn", text: "开始抽奖"}
5: {id: 4, text: "奖品4", index: 3}
6: {id: 7, text: "奖品7", index: 6}
7: {id: 6, text: "奖品6", index: 5}
8: {id: 5, text: "奖品5", index: 4}
length: 9
*/
}
},
methods: {
// 传的item是点击当前元素
startLuck (item) {
// 如果当前元素的id不是btn,就不执行
if (item.id !== 'btn') return
this.activeIndex = null
this.lucky = null
setTimeout(() => { // 随机抽中奖品
this.lucky = Math.floor(Math.random() * 8)
// console.log('奖品是' + this.lucky) // 返回的是索引
console.log('奖品是' + this.list[this.lucky].text)
}, 1000)
// 执行动画
this.move(10)
},
move (time) {
if (time > 600) { // time大于600就减速执行
if (this.activeIndex !== this.lucky) { // 如果this.activeIndex 不等于 抽中的奖品this.lucky
setTimeout(() => {
const t = this.activeIndex + 1
this.activeIndex = t % 8
this.move(time + time * 0.05)
}, time)
} else {
// console.log('抽中的奖品是' + this.activeIndex) // 返回的是索引
console.log('抽中的奖品是' + this.list[this.activeIndex].text)
}
} else { // time小于600就原速执行
setTimeout(() => {
const t = this.activeIndex + 1
this.activeIndex = t % 8
this.move(time + time * 0.1)
}, time)
}
}
},
mounted () {
// console.log(this.mapList)
}
}
</script>
<style lang="scss">
.test02{
.prize{
width: 600px;
margin: 100px auto;
ul{
display: flex;
flex-wrap: wrap;
li{
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
border: 1px solid #000;
box-sizing: border-box;
&.active{
width: 200px;
height: 200px;
background-color: red;
opacity: 0.5;
}
&:nth-child(5){
background-color: red;
}
}
}
}
}
</style>
<!--
0 1 2
3 4
5 6 7
0 1 2
7 3
6 5 4
-->
效果图