我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!
今天就想做一个抽奖项目,奖品数据就用了掘金活动赠送的奖品,就用了自己最熟悉的vue2写了下来
项目效果
项目实现
html
- 就一个根容器,然后用弹性布局遍历抽奖数据
- 用动态class,标记抽奖,和抽奖结果
<div class="draw-container">
<div v-for="(item, i) in drawArr" :key="'抽奖数据' + item" @click="clickDrawFn(i)"
:class="{'active-draw': i === 4, 'shadow': i === result}" >{{item}}</div>
</div>
script
- 在created钩子函数准备用v-for遍历的索引数据
- 由于是弹性布局的页面,所以一组数据中的索引要满足抽奖顺序
- 数据要保证足够多
created () { // 准备数据
const item = [0, 1, 2, 5, 8, 7, 6, 3] // 一组数据
for (let i = 1; i <= 10; i++) {
this.sumArr.push(...item) // 数据要足够多,保证 200(每个) * 8(一组) * 10(10组) > 总时长
}
},
- 提示都写在代码旁边
- 每个的时间和总时长根据自己需求灵活调整
clickDrawFn (index) {
if (index !== 4 || !this.allowClick) return // 点击的不是抽奖或者已经点过
this.allowClick = false // 不允许点击
this.result = 0 // v-for遍历索引从0开始
let i = 0 // 索引也从0开始
const timer = setInterval(() => {
this.result = this.sumArr[i]
i++
if (i === 8) { // 当索引为8时,重置索引
i = 0
}
}, 200) // 每个的时间
const randomTime = Math.random() + 1 // 排除随机数为0时
const timer1 = setTimeout(() => {
clearInterval(timer)
clearTimeout(timer1)
this.allowClick = true
// 时间到了。清除所有定时器,允许点击
}, 2000 * randomTime) // 总时长
}
css
- 用的都是一些常见的样式
- 要注意动态样式的权重问题,权重低了会不起作用
.shadow{
background: rgb(99, 97, 97)!important;
}
.active-draw{
background: green!important;
color: #fff;
cursor: pointer;
}
.draw-container{
width: 300px;
display: flex;
flex-wrap: wrap;
div{
flex: 26%;
margin: 5px;
padding: 15px 5px;
background: #eee;
text-align: center;
}
}