…">
当前位置:首页 > 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.js 本身是一个前端框架,主要用于构建用户界面。要实现爬虫功能,通常需要结合后端技术或浏览器自动化工具。以下是几种常见的方法: 方法一:Vue + Node.js…

vue实现数据

vue实现数据

Vue 实现数据绑定的方法 Vue.js 提供了多种方式实现数据绑定,包括双向绑定、单向绑定以及动态数据绑定。以下是几种常见的实现方式: 双向数据绑定(v-model) 双向数据绑定通常用于表单元素…

vue 实现table

vue 实现table

Vue 实现 Table 的方法 使用原生 HTML 表格 通过 Vue 的 v-for 指令动态渲染表格数据,适合简单表格场景。 <template> <table>…

vue实现回顶部

vue实现回顶部

实现方法一:使用 window.scrollTo 在Vue组件中,可以通过调用 window.scrollTo 方法平滑滚动到页面顶部。该方法接受一个配置对象,指定滚动行为为平滑(smooth)。…

vue实现折叠组件

vue实现折叠组件

Vue 折叠组件实现方法 基于 v-show 和事件触发 通过 v-show 控制内容的显示与隐藏,结合点击事件切换状态。 <template> <div> &…

vue怎么实现滑动

vue怎么实现滑动

Vue实现滑动效果的方法 在Vue中实现滑动效果可以通过多种方式,以下是几种常见的方法: 使用CSS过渡和动画 通过Vue的过渡系统和CSS可以实现平滑的滑动效果。定义一个CSS类,利用transf…