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>
直接上代码,里面有注释
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通