vue代码抛硬币实现
实现思路
使用Vue的数据绑定和事件处理功能,通过随机数生成模拟抛硬币的正反面结果,并添加动画效果增强交互体验。

基础实现代码
<template>
<div class="coin-container">
<div
class="coin"
:class="{ 'heads': isHeads, 'tails': !isHeads, 'flipping': isFlipping }"
@click="flipCoin"
>
{{ coinFace }}
</div>
<p>点击硬币进行抛掷</p>
<p>历史记录: {{ history.join(', ') }}</p>
</div>
</template>
<script>
export default {
data() {
return {
isHeads: true,
isFlipping: false,
history: []
}
},
computed: {
coinFace() {
return this.isHeads ? '正面' : '反面'
}
},
methods: {
flipCoin() {
if (this.isFlipping) return
this.isFlipping = true
setTimeout(() => {
this.isHeads = Math.random() > 0.5
this.history.push(this.coinFace)
this.isFlipping = false
}, 1000)
}
}
}
</script>
<style>
.coin-container {
text-align: center;
margin-top: 50px;
}
.coin {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: gold;
display: inline-flex;
justify-content: center;
align-items: center;
font-size: 20px;
cursor: pointer;
transition: transform 1s ease-out;
box-shadow: 0 0 10px rgba(0,0,0,0.3);
}
.coin.flipping {
transform: rotateY(1800deg);
}
.heads {
background-color: gold;
}
.tails {
background-color: silver;
}
</style>
功能扩展建议
-
添加音效增强体验

// 在methods中添加 playSound() { const audio = new Audio('coin-flip-sound.mp3') audio.play() } // 在flipCoin方法中调用 -
统计功能
data() { return { stats: { heads: 0, tails: 0 } } }, methods: { updateStats() { this.isHeads ? this.stats.heads++ : this.stats.tails++ } } -
3D翻转效果改进
.coin { transform-style: preserve-3d; } .coin:before, .coin:after { content: ''; position: absolute; width: 100%; height: 100%; border-radius: 50%; backface-visibility: hidden; } .coin:before { background: gold; transform: rotateY(0deg); } .coin:after { background: silver; transform: rotateY(180deg); }
注意事项
- 动画持续时间应与随机结果生成时间匹配
- 防止连续快速点击导致动画异常
- 移动端适配可考虑添加触摸事件支持
- 如需更真实效果,可引入物理引擎库模拟抛掷轨迹






