…">
当前位置:首页 > VUE

vue 2.0实现小球

2026-01-19 16:01:49VUE

使用Vue 2.0实现小球动画

在Vue 2.0中实现小球动画可以通过数据绑定和CSS动画结合完成。以下是一个完整的实现示例:

创建Vue实例与模板结构

<div id="app">
  <div class="ball" :style="ballStyle"></div>
  <button @click="moveBall">移动小球</button>
</div>

定义Vue组件逻辑

new Vue({
  el: '#app',
  data: {
    position: { x: 0, y: 0 },
    colors: ['#FF5252', '#FF4081', '#E040FB', '#7C4DFF', '#536DFE'],
    currentColor: 0
  },
  computed: {
    ballStyle() {
      return {
        transform: `translate(${this.position.x}px, ${this.position.y}px)`,
        backgroundColor: this.colors[this.currentColor]
      }
    }
  },
  methods: {
    moveBall() {
      this.position.x = Math.random() * 300
      this.position.y = Math.random() * 300
      this.currentColor = (this.currentColor + 1) % this.colors.length
    }
  }
})

添加CSS样式

.ball {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #FF5252;
  transition: all 0.5s ease;
  position: absolute;
}

实现拖拽功能

如需实现小球拖拽,可添加以下代码:

methods: {
  startDrag(e) {
    document.addEventListener('mousemove', this.drag)
    document.addEventListener('mouseup', this.stopDrag)
  },
  drag(e) {
    this.position.x = e.clientX - 25
    this.position.y = e.clientY - 25
  },
  stopDrag() {
    document.removeEventListener('mousemove', this.drag)
    document.removeEventListener('mouseup', this.stopDrag)
  }
}

并在模板中添加:

<div class="ball" 
     :style="ballStyle"
     @mousedown="startDrag"></div>

添加弹跳动画

通过CSS关键帧实现弹跳效果:

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-50px); }
}

.ball {
  animation: bounce 1s infinite;
}

使用第三方动画库

如需更复杂动画,可引入Vue过渡或第三方库如Animate.css:

vue 2.0实现小球

<transition 
  enter-active-class="animated bounceIn"
  leave-active-class="animated bounceOut">
  <div class="ball" v-if="showBall"></div>
</transition>

标签: 小球vue
分享给朋友:

相关文章

vue前端实现注册

vue前端实现注册

使用 Vue 实现用户注册功能 环境准备 确保已安装 Vue CLI 或通过 CDN 引入 Vue。若使用 Vue CLI,需安装 axios 或其他 HTTP 库用于后端通信。 注册表单组件 创建…

vue手动实现弹窗

vue手动实现弹窗

实现弹窗组件的基本结构 在Vue中手动实现弹窗组件,需要创建一个独立的弹窗组件,并通过props控制其显示与隐藏。弹窗组件通常包含遮罩层、内容区域和关闭按钮。 <template>…

vue优秀实现

vue优秀实现

Vue.js 优秀实现方法 响应式数据管理 使用 Vue 的 ref 和 reactive 处理基础类型和对象类型数据,结合 computed 计算属性优化渲染性能。对于复杂状态,推荐 Pinia 替…

代码实现vue

代码实现vue

创建Vue项目 使用Vue CLI快速初始化项目,确保已安装Node.js和npm/yarn: npm install -g @vue/cli vue create my-vue-project c…

vue实现标签

vue实现标签

Vue 实现标签的方法 在 Vue 中实现标签功能可以通过多种方式完成,以下是几种常见的方法: 使用动态组件 动态组件可以根据不同的条件渲染不同的标签内容。通过 :is 属性动态绑定组件名,实现标签…

vue实现toast

vue实现toast

Vue 实现 Toast 的方法 使用第三方库(推荐) 对于快速实现 Toast 功能,推荐使用成熟的第三方库如 vue-toastification 或 vant 的 Toast 组件。 安装 v…