vue实现骰子
Vue 实现骰子功能
创建 Vue 组件
在 Vue 项目中创建一个骰子组件,例如 Dice.vue。该组件包含骰子的外观和逻辑。
<template>
<div class="dice" @click="rollDice">
<div class="face" :class="'face-' + currentFace">
{{ currentFace }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentFace: 1,
rolling: false
}
},
methods: {
rollDice() {
if (this.rolling) return
this.rolling = true
const rolls = 10 + Math.floor(Math.random() * 10)
let rollCount = 0
const rollInterval = setInterval(() => {
this.currentFace = Math.floor(Math.random() * 6) + 1
rollCount++
if (rollCount >= rolls) {
clearInterval(rollInterval)
this.rolling = false
}
}, 100)
}
}
}
</script>
<style scoped>
.dice {
width: 100px;
height: 100px;
perspective: 1000px;
cursor: pointer;
}
.face {
width: 100%;
height: 100%;
position: absolute;
border-radius: 10px;
background: white;
border: 2px solid #333;
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem;
font-weight: bold;
transition: transform 0.5s;
}
.face-1 { transform: rotateX(0deg) rotateY(0deg); }
.face-2 { transform: rotateX(-90deg) rotateY(0deg); }
.face-3 { transform: rotateX(0deg) rotateY(90deg); }
.face-4 { transform: rotateX(0deg) rotateY(-90deg); }
.face-5 { transform: rotateX(90deg) rotateY(0deg); }
.face-6 { transform: rotateX(180deg) rotateY(0deg); }
</style>
使用 CSS 动画增强效果
为了更好的视觉效果,可以添加 CSS 动画使骰子旋转更自然。
@keyframes roll {
0% { transform: rotateX(0deg) rotateY(0deg); }
25% { transform: rotateX(180deg) rotateY(180deg); }
50% { transform: rotateX(360deg) rotateY(360deg); }
75% { transform: rotateX(540deg) rotateY(540deg); }
100% { transform: rotateX(720deg) rotateY(720deg); }
}
.dice.rolling .face {
animation: roll 1s infinite;
}
在父组件中使用
在需要使用骰子的父组件中引入并注册 Dice 组件。

<template>
<div>
<h3>点击骰子开始滚动</h3>
<Dice />
</div>
</template>
<script>
import Dice from './Dice.vue'
export default {
components: {
Dice
}
}
</script>
添加声音效果(可选)
为了增强用户体验,可以添加骰子滚动的声音效果。
// 在 rollDice 方法中添加
const audio = new Audio('dice-roll.mp3')
audio.play()
响应式设计
确保骰子在不同设备上都能正常显示,可以添加媒体查询调整大小。

@media (max-width: 600px) {
.dice {
width: 80px;
height: 80px;
}
}
可配置属性
使骰子组件更灵活,允许从父组件传入大小、颜色等属性。
props: {
size: {
type: Number,
default: 100
},
color: {
type: String,
default: '#333'
}
}
然后在模板和样式中使用这些 props:
<div class="dice" :style="{ width: size + 'px', height: size + 'px' }">
<div class="face" :style="{ borderColor: color }">
{{ currentFace }}
</div>
</div>






