feat: 优化九宫格抽奖
This commit is contained in:
parent
e63aa25902
commit
5787d29fbc
@ -28,15 +28,17 @@
|
||||
<script lang="ts" setup>
|
||||
import { reactive, computed } from 'vue'
|
||||
|
||||
const giftLen = 8 // 九宫格有8个礼物
|
||||
const loop = 4 // 设置转多少圈,在最后一圈会慢下来
|
||||
const totalStep = giftLen * loop // 总的步数 32
|
||||
const lastLoopStep = totalStep - giftLen // 最后一圈,24
|
||||
const numList = [1, 2, 3, 8, -1, 4, 7, 6, 5]
|
||||
|
||||
const btnIndex = numList[4] // 最中间那个是展示按钮
|
||||
// const activeIndex = ref(0)
|
||||
|
||||
const state = reactive({
|
||||
lottery: 0, // 奖品
|
||||
step: -1, // 目前转动的步数
|
||||
stopStep: 32, // 目标步数,上面我们有提到默认都会转几圈,这里默认转四圈,一圈有八个格子,四圈就是要转动32步
|
||||
stopStep: totalStep, // 停下来的时需要走的步数
|
||||
speed: 2, // 转动速度,我们是通过定时器去实现转动效果的,所以这也就是定时器的执行频率
|
||||
timer: null, // 定时器ID
|
||||
loading: false,
|
||||
@ -46,7 +48,7 @@ const activeIndex = computed(() => {
|
||||
return (state.step % 8) + 1
|
||||
})
|
||||
|
||||
function runFn() {
|
||||
function run() {
|
||||
// 当前步数大于等于目标步数
|
||||
if (state.step >= state.stopStep) {
|
||||
// 清空定时器,停止转动
|
||||
@ -55,17 +57,20 @@ function runFn() {
|
||||
state.step = state.lottery
|
||||
state.speed = 2
|
||||
state.loading = false
|
||||
console.log(`恭喜获得${state.lottery}号奖品`)
|
||||
console.log(`恭喜获得${activeIndex.value}号奖品`)
|
||||
uni.showModal({
|
||||
title: `恭喜获得${activeIndex.value}号奖品`,
|
||||
})
|
||||
return
|
||||
}
|
||||
// 转动到最后一圈时,增加speed,也就是定时器执行间隔时间变长,转动速度变慢
|
||||
if (state.step > 24 + state.lottery) {
|
||||
if (state.step > lastLoopStep + state.lottery) {
|
||||
state.speed++
|
||||
}
|
||||
// 抽奖函数每执行一次,当前步数加一
|
||||
state.step++
|
||||
// 重新开启定时器执行抽奖函数
|
||||
state.timer = setTimeout(runFn, state.speed * 30)
|
||||
state.timer = setTimeout(run, state.speed * 30)
|
||||
}
|
||||
// 点击抽奖之后调用的函数
|
||||
function handleClick(n) {
|
||||
@ -75,12 +80,12 @@ function handleClick(n) {
|
||||
if (state.loading) return
|
||||
state.loading = true
|
||||
// 最终获得的奖品,实际业务中是通过接口获取的,这里使用随机数来模拟下
|
||||
state.lottery = Math.floor(Math.random() * 9)
|
||||
state.lottery = Math.ceil(Math.random() * giftLen)
|
||||
console.log(state.lottery)
|
||||
// 计算总共要转动的步数,转4圈后再转到奖品处
|
||||
state.stopStep = state.lottery + 32
|
||||
state.stopStep = state.lottery + totalStep
|
||||
// 执行抽奖函数
|
||||
runFn()
|
||||
run()
|
||||
}
|
||||
</script>
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user