vue抽奖代码实现
Vue 抽奖代码实现
基础抽奖组件结构
使用 Vue 3 的 Composition API 实现抽奖功能,核心包括转盘动画、奖品列表和抽奖逻辑。以下为组件基础结构:

<template>
<div class="lottery-container">
<div class="wheel" :style="wheelStyle" @click="startLottery">
<div class="prize" v-for="(prize, index) in prizes" :key="index"
:style="getPrizeStyle(index)">
{{ prize.name }}
</div>
</div>
<button :disabled="isRotating" @click="startLottery">开始抽奖</button>
</div>
</template>
数据与样式计算
<script setup>
import { ref, computed } from 'vue'
const prizes = ref([
{ name: '奖品1', color: '#FF5252' },
{ name: '奖品2', color: '#FF4081' },
// 更多奖品...
])
const isRotating = ref(false)
const currentRotation = ref(0)
const wheelStyle = computed(() => ({
transform: `rotate(${currentRotation.value}deg)`,
transition: isRotating.value ? 'transform 4s ease-out' : 'none'
}))
const getPrizeStyle = (index) => {
const angle = 360 / prizes.value.length
return {
transform: `rotate(${angle * index}deg)`,
backgroundColor: prizes.value[index].color
}
}
</script>
抽奖逻辑实现
const startLottery = () => {
if (isRotating.value) return
isRotating.value = true
const targetRotation = currentRotation.value + 360 * 5 + Math.random() * 360
currentRotation.value = targetRotation
setTimeout(() => {
isRotating.value = false
const prizeIndex = calculatePrizeIndex(targetRotation % 360)
alert(`恭喜获得: ${prizes.value[prizeIndex].name}`)
}, 4000)
}
const calculatePrizeIndex = (finalAngle) => {
const sectorAngle = 360 / prizes.value.length
return Math.floor((360 - finalAngle) / sectorAngle) % prizes.value.length
}
CSS 样式
<style scoped>
.lottery-container {
display: flex;
flex-direction: column;
align-items: center;
}
.wheel {
width: 300px;
height: 300px;
border-radius: 50%;
position: relative;
overflow: hidden;
margin-bottom: 20px;
}
.prize {
position: absolute;
width: 50%;
height: 50%;
left: 50%;
top: 0;
transform-origin: left bottom;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
}
</style>
高级功能扩展
-
API 集成:通过 axios 从后端获取奖品列表和中奖结果

const fetchPrizes = async () => { const response = await axios.get('/api/prizes') prizes.value = response.data } -
概率控制:为不同奖品设置不同中奖概率
const weightedPrizes = [ { name: '特等奖', weight: 1 }, { name: '一等奖', weight: 5 }, // ... ]
const getRandomPrize = () => { const totalWeight = weightedPrizes.reduce((sum, p) => sum + p.weight, 0) let random = Math.random() * totalWeight return weightedPrizes.find(p => (random -= p.weight) <= 0) }
3. 动画优化:使用 GSAP 实现更流畅的动画效果
```javascript
import gsap from 'gsap'
const animateWheel = (targetAngle) => {
gsap.to(currentRotation, {
value: targetAngle,
duration: 4,
ease: "elastic.out(1, 0.3)",
onComplete: () => { /* 回调逻辑 */ }
})
}
注意事项
- 移动端适配需调整转盘尺寸和触摸事件
- 中奖结果应通过服务端验证防止作弊
- 高频率抽奖需添加防抖限制
- 奖品区域建议使用 SVG 实现更精确的角度计算






