vue实现人员滚动抽奖
Vue实现人员滚动抽奖
核心思路
通过Vue的数据绑定和动画特性,结合JavaScript定时器实现人员名单的滚动效果,最终随机停止并显示中奖结果。
实现步骤
准备数据与基础模板

<template>
<div class="lottery-container">
<div class="lottery-display">{{ currentName }}</div>
<button @click="startLottery" :disabled="isRolling">开始抽奖</button>
</div>
</template>
<script>
export default {
data() {
return {
names: ['张三', '李四', '王五', '赵六', '钱七', '孙八'],
currentName: '准备开始',
isRolling: false,
timer: null,
rollSpeed: 100
}
}
}
</script>
实现滚动逻辑
methods: {
startLottery() {
this.isRolling = true
this.currentName = '抽奖中...'
this.timer = setInterval(() => {
const randomIndex = Math.floor(Math.random() * this.names.length)
this.currentName = this.names[randomIndex]
}, this.rollSpeed)
setTimeout(() => {
clearInterval(this.timer)
this.isRolling = false
this.finalResult()
}, 3000)
},
finalResult() {
const winnerIndex = Math.floor(Math.random() * this.names.length)
this.currentName = `中奖者: ${this.names[winnerIndex]}`
}
}
添加CSS动画效果

<style scoped>
.lottery-container {
text-align: center;
margin-top: 50px;
}
.lottery-display {
font-size: 24px;
height: 40px;
margin: 20px 0;
transition: all 0.3s;
}
button {
padding: 10px 20px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:disabled {
background-color: #cccccc;
}
</style>
高级优化方案
增加加速度效果
// 修改startLottery方法
startLottery() {
this.isRolling = true
let duration = 3000
let startTime = Date.now()
const roll = () => {
if (Date.now() - startTime >= duration) {
clearInterval(this.timer)
this.finalResult()
this.isRolling = false
return
}
const elapsed = Date.now() - startTime
const progress = elapsed / duration
this.rollSpeed = 100 + (500 * (1 - progress))
clearInterval(this.timer)
this.timer = setInterval(() => {
const randomIndex = Math.floor(Math.random() * this.names.length)
this.currentName = this.names[randomIndex]
}, this.rollSpeed)
requestAnimationFrame(roll)
}
roll()
}
添加音效支持
<audio ref="rollSound" src="rolling-sound.mp3"></audio>
<audio ref="winSound" src="win-sound.mp3"></audio>
<!-- 在methods中添加 -->
playSound(refName) {
this.$refs[refName].currentTime = 0
this.$refs[refName].play()
}
注意事项
- 移动端适配可能需要调整字体大小和按钮尺寸
- 长时间抽奖应考虑使用Web Worker防止主线程阻塞
- 大量数据时应采用虚拟滚动技术优化性能
- 中奖逻辑可根据需求改为权重算法或排除已中奖人员






