vue实现砸金蛋
Vue 实现砸金蛋功能
准备工作
确保已安装 Vue.js 环境,可以通过以下命令创建项目:
npm init vue@latest
组件结构设计
创建 GoldenEgg.vue 文件,包含以下核心结构:
<template>
<div class="egg-container">
<div
class="egg"
:class="{ 'egg-broken': isBroken }"
@click="hitEgg"
>
<div v-if="!isBroken">🎁</div>
<div v-else class="prize">{{ prize }}</div>
</div>
</div>
</template>
数据与逻辑实现
<script>
export default {
data() {
return {
isBroken: false,
prizes: ['100元', '优惠券', '谢谢参与', '神秘大奖'],
prize: ''
}
},
methods: {
hitEgg() {
if (this.isBroken) return;
// 随机选择奖品
const randomIndex = Math.floor(Math.random() * this.prizes.length);
this.prize = this.prizes[randomIndex];
// 触发动画
this.isBroken = true;
// 重置功能(可选)
setTimeout(() => {
this.isBroken = false;
}, 3000);
}
}
}
</script>
样式设计
<style scoped>
.egg-container {
display: flex;
justify-content: center;
margin-top: 50px;
}
.egg {
width: 200px;
height: 250px;
background-color: #FFD700;
border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
display: flex;
justify-content: center;
align-items: center;
font-size: 60px;
cursor: pointer;
transition: all 0.5s ease;
box-shadow: 0 10px 25px rgba(0,0,0,0.2);
}
.egg-broken {
transform: scale(0.9);
background-color: #FFA500;
animation: shake 0.5s;
}
.prize {
font-size: 24px;
color: white;
text-align: center;
}
@keyframes shake {
0% { transform: rotate(0deg); }
25% { transform: rotate(-5deg); }
50% { transform: rotate(5deg); }
75% { transform: rotate(-5deg); }
100% { transform: rotate(0deg); }
}
</style>
进阶功能
添加音效增强体验:
<template>
<audio ref="crackSound" src="@/assets/crack.mp3" preload="auto"></audio>
</template>
<script>
methods: {
hitEgg() {
this.$refs.crackSound.play();
// ...原有逻辑
}
}
</script>
多蛋排列方案
<div class="egg-group">
<GoldenEgg v-for="(egg, index) in 5" :key="index" />
</div>
<style>
.egg-group {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
</style>
注意事项
- 音效文件需放在
public或assets目录 - 移动端需添加
@touchstart事件支持触摸 - 奖品概率可通过加权数组实现:
prizes: [ { name: '100元', weight: 1 }, { name: '优惠券', weight: 3 } ]







