当前位置:首页 > VUE

vue实现砸金蛋

2026-03-29 20:05:06VUE

实现砸金蛋的Vue组件

准备工作

安装Vue和相关依赖

npm install vue hammerjs

组件结构

创建金蛋组件模板

<template>
  <div class="egg-container">
    <div 
      class="egg" 
      @click="crackEgg"
      :class="{ 'cracked': isCracked }"
    >
      <div class="prize" v-if="isCracked">
        {{ prize }}
      </div>
    </div>
  </div>
</template>

组件逻辑

实现砸蛋交互功能

<script>
export default {
  data() {
    return {
      isCracked: false,
      prize: '',
      prizes: ['一等奖', '二等奖', '谢谢参与']
    }
  },
  methods: {
    crackEgg() {
      if(this.isCracked) return;

      this.isCracked = true;
      const randomIndex = Math.floor(Math.random() * this.prizes.length);
      this.prize = this.prizes[randomIndex];

      // 触发父组件事件
      this.$emit('egg-cracked', this.prize);
    }
  }
}
</script>

样式设计

添加金蛋动画效果

<style scoped>
.egg-container {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.egg {
  width: 150px;
  height: 200px;
  background: linear-gradient(to bottom, #FFD700, #FFA500);
  border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
  cursor: pointer;
  position: relative;
  box-shadow: 0 10px 15px rgba(0,0,0,0.2);
  transition: transform 0.3s;
}

.egg:hover {
  transform: scale(1.05);
}

.cracked {
  background: linear-gradient(to bottom, #D3D3D3, #A9A9A9);
  animation: crack 0.5s forwards;
}

.prize {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  font-weight: bold;
  color: #FF4500;
}

@keyframes crack {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}
</style>

使用组件

在父组件中使用金蛋组件

<template>
  <div>
    <h3>砸金蛋游戏</h3>
    <EggComponent @egg-cracked="handlePrize" />
  </div>
</template>

<script>
import EggComponent from './EggComponent.vue';

export default {
  components: {
    EggComponent
  },
  methods: {
    handlePrize(prize) {
      alert(`恭喜获得: ${prize}`);
    }
  }
}
</script>

增强功能

添加Hammer.js实现手势操作

vue实现砸金蛋

import Hammer from 'hammerjs';

mounted() {
  const hammer = new Hammer(this.$el.querySelector('.egg'));
  hammer.on('swipe', () => {
    this.crackEgg();
  });
}

注意事项

  1. 确保组件样式隔离使用scoped
  2. 考虑移动端适配添加响应式设计
  3. 可以扩展更多动画效果增强交互体验
  4. 奖品数据可以从后端API动态获取

标签: vue砸金蛋
分享给朋友:

相关文章

vue实现旋转

vue实现旋转

Vue 实现旋转效果的方法 在 Vue 中实现旋转效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 动画 通过 Vue 的 :class 或 :style 绑定 CSS 动画实现旋转效…

vue实现骰子

vue实现骰子

Vue 实现骰子功能 创建 Vue 组件 在 Vue 项目中创建一个骰子组件,例如 Dice.vue。该组件包含骰子的外观和逻辑。 <template> <div class=…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue实现白板

vue实现白板

Vue实现白板功能 使用Vue实现白板功能可以通过HTML5的Canvas API结合Vue的响应式特性来完成。以下是实现白板功能的关键步骤: 安装依赖 在Vue项目中安装必要的依赖,如vue-dr…

vue实现尺子

vue实现尺子

Vue 实现尺子组件 实现一个尺子组件可以通过 Canvas 或纯 CSS 完成。以下是两种常见实现方式: 使用 Canvas 绘制尺子 通过 Canvas 动态绘制刻度线和数字,适合需要高精度或动…

实现简单vue

实现简单vue

实现一个简单的 Vue.js 框架 Vue.js 的核心功能包括数据绑定、响应式系统和虚拟 DOM。以下是一个简化版的 Vue 实现,涵盖基本功能。 数据响应式系统 使用 Object.define…