vue 2.0实现小球
使用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:
<transition
enter-active-class="animated bounceIn"
leave-active-class="animated bounceOut">
<div class="ball" v-if="showBall"></div>
</transition>






