…">
当前位置:首页 > 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 中实现页面返回功能,可以通过以下几种方式完成,具体取决于项目使用的路由模式和技术栈。 使用 Vue Router 的编程式导航 通过 this.$router…

vue实现alert

vue实现alert

实现自定义 Alert 组件 在 Vue 中可以通过组件化方式实现自定义 Alert 弹窗。以下是基于 Vue 3 的实现示例: 组件代码 (Alert.vue) <template>…

vue实现xss

vue实现xss

XSS 攻击简介 XSS(跨站脚本攻击)是一种常见的安全漏洞,攻击者通过注入恶意脚本到网页中,当其他用户访问该页面时,脚本会在其浏览器中执行,可能导致数据泄露或会话劫持。 Vue 中的 XSS…

vue mvvm实现

vue mvvm实现

Vue MVVM 实现原理 Vue.js 是一个基于 MVVM(Model-View-ViewModel)模式的框架,其核心是通过数据绑定和响应式系统实现视图与数据的自动同步。以下是 Vue 实现 M…

vue事件实现

vue事件实现

Vue 事件实现方法 在Vue中,事件处理是通过v-on指令或@简写来实现的。以下是几种常见的事件处理方式: 使用v-on指令绑定事件 <button v-on:click="handleC…

vue删除实现

vue删除实现

Vue 删除功能的实现方法 在 Vue 中实现删除功能通常涉及以下几个步骤: 方法一:使用数组的 splice 方法 通过索引删除数组中的元素,适用于列表渲染的场景。 methods: {…