2020-05-05 06:51:25
使用Vue.js制作大转盘的核心步骤如下:
一、基础结构搭建创建Vue组件
<template> <div class="turntable-container"> <div class="wheel" :style="{transform: `rotate(${currentRotate}deg)`}"> <div v-for="(item, index) in prizeList" :key="index" class="sector" :style="getSectorStyle(index)"> {{item.name}} </div> </div> <button @click="startRotate">开始抽奖</button> </div></template>数据定义
data() { return { prizeList: [ {name: "一等奖", probability: 10}, {name: "二等奖", probability: 20}, // ...其他奖项 ], currentRotate: 0, isRotating: false }}转盘样式计算
methods: { getSectorStyle(index) { const count = this.prizeList.length const angle = 360 / count return { transform: `rotate(${angle * index}deg)`, clipPath: `polygon(50% 50%, 50% 0, ${50 + 100 * Math.cos((angle * index) * Math.PI / 180)}% ${50 + 100 * Math.sin((angle * index) * Math.PI / 180)}%)` } }}旋转动画控制
methods: { startRotate() { if (this.isRotating) return this.isRotating = true // 计算目标奖项 const random = Math.random() * 100 let probabilitySum = 0 const targetIndex = this.prizeList.findIndex(item => { probabilitySum += item.probability return random <= probabilitySum }) // 计算旋转角度(基础5圈+目标角度) const baseRotate = 1800 const targetAngle = 360 / this.prizeList.length * targetIndex this.currentRotate = baseRotate + targetAngle // 添加回弹效果 setTimeout(() => { this.currentRotate += 15 // 回弹角度 setTimeout(() => { this.currentRotate -= 15 this.isRotating = false }, 300) }, baseRotate / 360 * 1000) }}拖拽排序功能
// 安装vuedraggable后import draggable from 'vuedraggable'components: { draggable },<draggable v-model="prizeList" handle=".handle"> <div v-for="(item, index) in prizeList" :key="index"> <span class="handle">≡</span> <input v-model="item.name"> <input v-model.number="item.probability" type="number"> </div></draggable>配置保存功能
methods: { saveConfig() { localStorage.setItem('turntableConfig', JSON.stringify({ prizes: this.prizeList, settings: {/* 其他设置 */} })) }, loadConfig() { const config = JSON.parse(localStorage.getItem('turntableConfig')) if (config) { this.prizeList = config.prizes // 恢复其他设置 } }}使用CSS transform实现高性能旋转
通过transition的cubic-bezier实现缓动效果
添加回弹动画增强体验

完整实现可参考:
这个实现包含了:
通过Vue的响应式特性,所有配置变更都会实时反映在转盘上,适合作为营销活动或抽奖游戏的组件使用。