vue实现骰子
Vue 实现骰子功能
创建基本骰子组件
使用 Vue 单文件组件实现骰子的基本结构,包括模板、样式和逻辑。骰子的六个面可以通过 CSS 3D 变换实现立体效果。
<template>
<div class="dice-container">
<div class="dice" :class="'show-' + currentFace">
<div class="face face-1">1</div>
<div class="face face-2">2</div>
<div class="face face-3">3</div>
<div class="face face-4">4</div>
<div class="face face-5">5</div>
<div class="face face-6">6</div>
</div>
<button @click="rollDice">Roll Dice</button>
</div>
</template>
<script>
export default {
data() {
return {
currentFace: 1
}
},
methods: {
rollDice() {
this.currentFace = Math.floor(Math.random() * 6) + 1
}
}
}
</script>
<style scoped>
.dice-container {
perspective: 1000px;
margin: 50px;
}
.dice {
width: 100px;
height: 100px;
position: relative;
transform-style: preserve-3d;
transition: transform 1s;
}
.face {
position: absolute;
width: 100%;
height: 100%;
border: 2px solid #000;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
background: white;
}
/* 骰子各面定位 */
.face-1 { transform: rotateY(0deg) translateZ(50px); }
.face-2 { transform: rotateY(90deg) translateZ(50px); }
.face-3 { transform: rotateY(180deg) translateZ(50px); }
.face-4 { transform: rotateY(-90deg) translateZ(50px); }
.face-5 { transform: rotateX(90deg) translateZ(50px); }
.face-6 { transform: rotateX(-90deg) translateZ(50px); }
/* 显示当前面 */
.show-1 { transform: rotateY(0deg); }
.show-2 { transform: rotateY(-90deg); }
.show-3 { transform: rotateY(-180deg); }
.show-4 { transform: rotateY(90deg); }
.show-5 { transform: rotateX(-90deg); }
.show-6 { transform: rotateX(90deg); }
</style>
添加动画效果
为骰子滚动添加更逼真的动画效果,使用 CSS 关键帧动画模拟骰子旋转过程。

.dice {
animation: roll 1s ease-out;
}
@keyframes roll {
0% { transform: rotateX(0deg) rotateY(0deg); }
100% { transform: rotateX(720deg) rotateY(360deg); }
}
实现多个骰子
扩展组件以支持多个骰子同时滚动,并计算总点数。

<template>
<div>
<div class="dices">
<div
v-for="(dice, index) in dices"
:key="index"
class="dice"
:class="'show-' + dice.value"
>
<div class="face face-1">1</div>
<div class="face face-2">2</div>
<div class="face face-3">3</div>
<div class="face face-4">4</div>
<div class="face face-5">5</div>
<div class="face face-6">6</div>
</div>
</div>
<button @click="rollAll">Roll All</button>
<p>Total: {{ total }}</p>
</div>
</template>
<script>
export default {
data() {
return {
dices: [
{ value: 1 },
{ value: 1 },
{ value: 1 }
]
}
},
computed: {
total() {
return this.dices.reduce((sum, dice) => sum + dice.value, 0)
}
},
methods: {
rollAll() {
this.dices.forEach(dice => {
dice.value = Math.floor(Math.random() * 6) + 1
})
}
}
}
</script>
添加音效
为骰子滚动添加音效增强用户体验,使用 HTML5 Audio API。
<template>
<button @click="rollWithSound">Roll With Sound</button>
</template>
<script>
export default {
methods: {
rollWithSound() {
const audio = new Audio('dice_sound.mp3')
audio.play()
this.rollDice()
}
}
}
</script>
响应式设计
确保骰子在不同设备上都能正常显示,添加响应式 CSS。
@media (max-width: 600px) {
.dice {
width: 80px;
height: 80px;
}
.face {
font-size: 20px;
}
}






