vue实现抽奖滚动
Vue 实现抽奖滚动效果
抽奖滚动效果可以通过 Vue 的过渡动画、定时器和随机数生成来实现。以下是一个完整的实现方案。
基础实现思路
使用 Vue 的 v-for 渲染奖品列表,结合 CSS 过渡动画和 JavaScript 定时器控制滚动效果。通过随机数决定最终停下的位置。
<template>
<div class="lottery-container">
<div class="prize-list" :style="{ transform: `translateY(${offset}px)` }">
<div class="prize-item" v-for="(item, index) in prizes" :key="index">
{{ item.name }}
</div>
</div>
<button @click="startLottery">开始抽奖</button>
</div>
</template>
<script>
export default {
data() {
return {
prizes: [
{ name: "奖品1" },
{ name: "奖品2" },
{ name: "奖品3" },
{ name: "奖品4" },
{ name: "奖品5" },
{ name: "奖品6" }
],
offset: 0,
isRolling: false,
targetIndex: 0,
speed: 50,
timer: null
};
},
methods: {
startLottery() {
if (this.isRolling) return;
this.isRolling = true;
this.targetIndex = Math.floor(Math.random() * this.prizes.length);
this.roll();
},
roll() {
this.offset -= this.speed;
if (this.offset < -this.targetIndex * 60) {
this.isRolling = false;
clearTimeout(this.timer);
return;
}
this.timer = setTimeout(this.roll, 100);
}
}
};
</script>
<style>
.lottery-container {
height: 300px;
overflow: hidden;
position: relative;
}
.prize-list {
transition: transform 0.1s linear;
}
.prize-item {
height: 60px;
line-height: 60px;
text-align: center;
border: 1px solid #eee;
}
</style>
增强动画效果
为了使滚动效果更自然,可以添加缓动函数和速度变化。
roll() {
this.speed = Math.max(5, this.speed * 0.98);
this.offset -= this.speed;
if (Math.abs(this.offset + this.targetIndex * 60) < 1) {
this.isRolling = false;
clearTimeout(this.timer);
return;
}
this.timer = setTimeout(this.roll, 50);
}
使用 Vue Transition
Vue 的 <transition-group> 可以更好地处理列表动画。
<template>
<div class="lottery-container">
<transition-group name="list" tag="div" class="prize-list">
<div class="prize-item" v-for="(item, index) in prizes" :key="index">
{{ item.name }}
</div>
</transition-group>
<button @click="startLottery">开始抽奖</button>
</div>
</template>
<style>
.list-move {
transition: transform 0.5s ease;
}
</style>
完整组件封装
将抽奖功能封装为可复用的组件,支持自定义奖品列表和回调函数。
// LotteryWheel.vue
export default {
props: {
items: {
type: Array,
required: true
},
duration: {
type: Number,
default: 3000
}
},
methods: {
start() {
return new Promise(resolve => {
// 滚动逻辑
setTimeout(() => {
const result = this.items[this.targetIndex];
resolve(result);
}, this.duration);
});
}
}
};
性能优化建议
对于大量奖品的情况,可以考虑虚拟滚动技术。使用 vue-virtual-scroller 等库只渲染可见区域的奖品项,提高性能。
import { RecycleScroller } from 'vue-virtual-scroller';
components: {
RecycleScroller
}
以上方案提供了从基础到进阶的 Vue 抽奖滚动实现方法,可根据实际需求选择适合的方案并进一步调整细节。







