vue实现转盘抽奖
Vue 实现转盘抽奖
准备工作
确保已安装 Vue.js 环境,推荐使用 Vue 3 版本。可以通过以下命令创建一个 Vue 项目:
npm init vue@latest
基本结构
在 Vue 组件中,转盘抽奖通常需要一个圆形转盘和触发按钮。HTML 结构如下:
<template>
<div class="wheel-container">
<div class="wheel" :style="wheelStyle" ref="wheel"></div>
<button @click="startSpin" :disabled="isSpinning">开始抽奖</button>
</div>
</template>
数据与样式
定义转盘的奖品数据和旋转样式:
<script>
export default {
data() {
return {
prizes: ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6'],
isSpinning: false,
rotation: 0
};
},
computed: {
wheelStyle() {
return {
transform: `rotate(${this.rotation}deg)`,
transition: this.isSpinning ? 'transform 3s ease-out' : 'none'
};
}
}
};
</script>
旋转逻辑
实现旋转动画和结果判定:
methods: {
startSpin() {
if (this.isSpinning) return;
this.isSpinning = true;
const spinDegrees = 360 * 5 + Math.floor(Math.random() * 360);
this.rotation += spinDegrees;
setTimeout(() => {
const prizeIndex = Math.floor((this.rotation % 360) / (360 / this.prizes.length));
alert(`恭喜获得: ${this.prizes[prizeIndex]}`);
this.isSpinning = false;
}, 3000);
}
}
样式设计
添加 CSS 样式使转盘可视化:
<style>
.wheel-container {
display: flex;
flex-direction: column;
align-items: center;
}
.wheel {
width: 300px;
height: 300px;
border-radius: 50%;
background: conic-gradient(
from 0deg,
red 0deg 60deg,
blue 60deg 120deg,
green 120deg 180deg,
yellow 180deg 240deg,
purple 240deg 300deg,
orange 300deg 360deg
);
margin-bottom: 20px;
}
button {
padding: 10px 20px;
font-size: 16px;
}
</style>
优化方向
- 奖品数量动态化:通过
v-for动态生成转盘扇形。 - 中奖概率控制:为每个奖品设置不同的概率权重。
- 动画平滑度:调整
transition-timing-function实现更自然的减速效果。
完整示例
以下是一个结合动态奖品和概率控制的改进版本:
data() {
return {
prizes: [
{ name: '一等奖', probability: 0.1 },
{ name: '二等奖', probability: 0.2 },
{ name: '三等奖', probability: 0.3 },
{ name: '谢谢参与', probability: 0.4 }
],
// 其他数据...
};
},
methods: {
getRandomPrize() {
const random = Math.random();
let cumulative = 0;
for (const prize of this.prizes) {
cumulative += prize.probability;
if (random <= cumulative) return prize;
}
return this.prizes[this.prizes.length - 1];
}
}






