vue实现九宫格抽奖案例
最近公司需要制作一个九宫格抽奖活动需求,自己先实现了一个简单模板
效果图

<template>
<div class="container">
<div
@click="start(item)"
v-for="item in list"
:key="item.title"
:class="{ active: activeIndex === item.activeIndex }"
>
<span>{{ item.title !== 0 ? item.content : '开始' }}</span>
</div>
</div>
</template>
<script>
export default {
name: 'JiuGongGe',
props: {},
data() {
return {
activeIndex: 1,
list: [
{
title: 1,
activeIndex: 1,
content: '谢谢惠顾',
},
{
title: 2,
activeIndex: 2,
content: '一等奖',
},
{
title: 3,
activeIndex: 3,
content: '谢谢惠顾',
},
{
title: 8,
activeIndex: 8,
content: '谢谢惠顾',
},
{
title: 0,
activeIndex: 0,
},
{
title: 4,
activeIndex: 4,
content: '三等奖',
},
{
title: 7,
activeIndex: 7,
content: '谢谢惠顾',
},
{
title: 6,
activeIndex: 6,
content: '二等奖',
},
{
title: 5,
activeIndex: 5,
content: '谢谢惠顾',
},
],
cicles: 0, //定义圈数
time: 400, //定义速度
}
},
methods: {
start(item) {
if (item.title !== 0) return
//轮盘转动
//定义一个随机数
const selectIndex = Math.round(Math.random() * 7) + 1
this.startView(selectIndex, () => {
//停止时的回调函数
const result = this.list.find((item) => {
return item.title === selectIndex
})
//输出结果
console.log('当前抽中:' + result.content)
})
},
startView(selectIndex, fn) {
// console.log(this.activeIndex, selectIndex)
if (this.activeIndex === selectIndex && this.cicles < 4) {
//圈数+1
this.cicles += 1
//速度加快
this.time -= 100
}
if (this.activeIndex === selectIndex && this.cicles >= 4) {
this.cicles += 1
//圈数>4时速度减慢
this.time += 100
}
if (this.cicles > 7 && this.activeIndex === selectIndex) {
//圈数为8时停止
fn()
return
}
let timer = setTimeout(() => {
//定时器轮询
if (this.activeIndex < 8) {
this.activeIndex++
} else {
this.activeIndex = 1
}
//每走一步清除定时器再递归调用,实现连续效果
clearTimeout(timer)
this.startView(selectIndex, fn)
}, this.time)
},
},
}
</script>
<style>
.container {
width: 660px;
height: 660px;
background-color: aliceblue;
display: flex;
flex-wrap: wrap;
align-items: flex-start;
}
.container div {
width: 200px;
height: 200px;
background-color: aqua;
margin: 10px;
}
.container div span {
font-size: 30px;
}
.active {
background-color: orange !important;
}
</style>
直接上代码,里面有注释

浙公网安备 33010602011771号