最近项目要推一个抽奖的九宫格活动。网上看了很多版本。但效果都不是很理想。最后还是自己试着写一下
data() {
return {
prizes: [1, 1, 1, 1, 1, 1, 1, 1, 1], // 奖品列表
currentIndex: -1, // 当前转动到哪个位置,起点位置
count: 8, // 总共有多少个位置
timer: 0, // 每次转动定时器
speed: 200, // 初始转动速度
times: 0, // 转动次数
cycle: 50, // 转动基本次数:
prize: -1, // 中奖位置
ranking: false
};
},
// 获取中奖
getLuckDrawIndex() {
this.startRoll()
//这里可以对接后台获取中奖的信息 来获取中奖的下标
this.prize = 2
},
//启动抽奖
startRoll() {
let vm = this
this.times += 1 // 转动次数
this.oneRoll()
if (this.times > this.cycle + 10 && this.prize === this.currentIndex) {
clearTimeout(this.timer) // 清除转动定时器,停止转动
this.prize = -1
this.times = 0
this.speed = 200
var that = this;
this.ranking = true
} else {
if (this.times < this.cycle) {
this.speed -= 10 // 加快转动速度
} else if (this.times === this.cycle) {
if (this.prize > 7) {
this.prize = 7
}
} else if (this.times > this.cycle + 10 && ((this.prize === 0 && this.currentIndex === 7) || this
.prize === this.currentIndex + 1)) {
this.speed += 110
} else {
this.speed += 20
}
if (this.speed < 40) {
this.speed = 40
}
this.timer = setTimeout(this.startRoll, this.speed)
}
},
// 每一次转动
oneRoll() {
let index = this.currentIndex // 当前转动到哪个位置
const count = this.count // 总共有多少个位置
index += 1
if (index > count - 1) {
index = 0
}
this.currentIndex = index
},
clearRoll() {
clearTimeout(this.timer) // 停止转动
this.prize = -1
this.times = 0
this.speed = 200
}