vue实现砸金蛋源码
Vue实现砸金蛋功能源码解析
砸金蛋功能通常包含动画效果、奖品展示和交互逻辑。以下是一个基于Vue 3的实现方案,使用Composition API和CSS动画。
核心组件结构
<template>
<div class="egg-game-container">
<div
class="golden-egg"
:class="{ 'egg-cracked': isCracked }"
@click="handleEggClick"
>
<div class="egg-top" v-if="!isCracked"></div>
<div class="egg-bottom"></div>
<div class="prize" v-if="showPrize">{{ prize }}</div>
</div>
</div>
</template>
组件逻辑实现
<script setup>
import { ref } from 'vue';
const isCracked = ref(false);
const showPrize = ref(false);
const prize = ref('');
const prizes = [
'一等奖',
'二等奖',
'三等奖',
'谢谢参与'
];
const handleEggClick = () => {
if (isCracked.value) return;
isCracked.value = true;
setTimeout(() => {
const randomIndex = Math.floor(Math.random() * prizes.length);
prize.value = prizes[randomIndex];
showPrize.value = true;
}, 800);
};
</script>
CSS动画样式
<style scoped>
.egg-game-container {
display: flex;
justify-content: center;
margin-top: 50px;
}
.golden-egg {
position: relative;
width: 200px;
height: 240px;
cursor: pointer;
}
.egg-top {
position: absolute;
top: 0;
width: 100%;
height: 40%;
background: #FFD700;
border-radius: 50% 50% 0 0;
box-shadow: 0 -5px 10px rgba(0,0,0,0.2);
transition: transform 0.5s ease;
}
.egg-bottom {
position: absolute;
bottom: 0;
width: 100%;
height: 60%;
background: #FFD700;
border-radius: 0 0 50% 50%;
box-shadow: 0 5px 10px rgba(0,0,0,0.2);
}
.egg-cracked .egg-top {
transform: translateY(-100%) rotate(30deg);
}
.prize {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 24px;
font-weight: bold;
color: #FF4500;
animation: fadeIn 0.5s;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
</style>
功能扩展建议
-
添加音效增强体验 在
handleEggClick方法中加入音频播放:const playSound = (soundFile) => { const audio = new Audio(soundFile); audio.play(); }; -
实现多蛋布局 修改模板为循环渲染多个金蛋:
<div v-for="(egg, index) in eggs" :key="index" class="golden-egg"> <!-- 单蛋内容 --> </div> -
添加点击限制 防止重复点击:
const handleEggClick = () => { if (isCracked.value || isAnimating.value) return; isAnimating.value = true; // ...原有逻辑 };
完整项目结构参考
/src
/components
GoldenEgg.vue
/assets
/sounds
crack.mp3
win.mp3
/images
egg-bg.png
该实现包含基础动画效果和奖品随机逻辑,可根据实际需求调整样式和交互细节。CSS动画部分使用了transform属性实现金蛋破裂效果,Vue的响应式系统管理状态变化。







