vue实现滚动抽奖
Vue 实现滚动抽奖功能
滚动抽奖是一种常见的互动形式,可以通过 Vue 实现动态效果。以下是实现滚动抽奖的关键步骤和代码示例。
数据准备
定义一个奖品列表和当前选中的奖品索引:
data() {
return {
prizes: ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5'],
currentIndex: 0,
isRolling: false,
rollSpeed: 100,
targetIndex: 0
}
}
滚动动画实现
使用 setInterval 实现滚动效果,通过逐渐减慢速度模拟抽奖过程:
methods: {
startRoll() {
if (this.isRolling) return
this.isRolling = true
this.targetIndex = Math.floor(Math.random() * this.prizes.length)
const rollInterval = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.prizes.length
if (this.currentIndex === this.targetIndex && this.rollSpeed > 300) {
clearInterval(rollInterval)
this.isRolling = false
} else if (this.rollSpeed < 300) {
this.rollSpeed += 10
}
}, this.rollSpeed)
}
}
模板渲染
在模板中显示奖品列表和当前选中项:
<div class="lottery-container">
<div
v-for="(prize, index) in prizes"
:key="index"
:class="{ 'active': index === currentIndex }"
>
{{ prize }}
</div>
<button @click="startRoll" :disabled="isRolling">开始抽奖</button>
</div>
CSS 样式
添加基本样式增强视觉效果:
.lottery-container {
display: flex;
flex-direction: column;
align-items: center;
}
.lottery-container div {
padding: 10px;
margin: 5px;
border: 1px solid #ddd;
}
.lottery-container div.active {
background-color: #ffeb3b;
font-weight: bold;
}
button {
margin-top: 20px;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:disabled {
background-color: #cccccc;
}
优化建议
- 可以添加缓动函数使滚动效果更自然
- 增加音效增强用户体验
- 考虑使用 CSS 动画替代 JavaScript 定时器
- 对于大量奖品,建议实现虚拟滚动优化性能
这种实现方式适用于简单的抽奖场景,如需更复杂效果可以考虑使用第三方动画库如 GSAP 或 Anime.js。







