vue实现小球自由移动
Vue 实现小球自由移动
在 Vue 中实现小球自由移动可以通过动态绑定样式、使用 requestAnimationFrame 或 CSS 动画来实现。以下是几种常见的方法:

方法一:动态绑定样式 + JavaScript 动画
通过 Vue 的 data 和 methods 动态更新小球的 left 和 top 值,结合 requestAnimationFrame 实现平滑动画。

<template>
<div class="ball" :style="{ left: x + 'px', top: y + 'px' }"></div>
</template>
<script>
export default {
data() {
return {
x: 0,
y: 0,
dx: 2,
dy: 2,
width: 800,
height: 600,
};
},
mounted() {
this.animate();
},
methods: {
animate() {
this.x += this.dx;
this.y += this.dy;
// 边界检测
if (this.x <= 0 || this.x >= this.width - 30) {
this.dx = -this.dx;
}
if (this.y <= 0 || this.y >= this.height - 30) {
this.dy = -this.dy;
}
requestAnimationFrame(this.animate);
},
},
};
</script>
<style>
.ball {
position: absolute;
width: 30px;
height: 30px;
background-color: red;
border-radius: 50%;
}
</style>
方法二:CSS 动画 + @keyframes
通过 CSS @keyframes 定义动画路径,利用 Vue 动态绑定类名或样式。
<template>
<div class="ball" :style="ballStyle"></div>
</template>
<script>
export default {
data() {
return {
duration: 5, // 动画时长(秒)
};
},
computed: {
ballStyle() {
return {
animation: `move ${this.duration}s linear infinite`,
};
},
},
};
</script>
<style>
.ball {
width: 30px;
height: 30px;
background-color: blue;
border-radius: 50%;
position: absolute;
}
@keyframes move {
0% {
transform: translate(0, 0);
}
25% {
transform: translate(200px, 100px);
}
50% {
transform: translate(400px, 0);
}
75% {
transform: translate(200px, -100px);
}
100% {
transform: translate(0, 0);
}
}
</style>
方法三:使用 Vue Transition
结合 Vue 的 <transition> 和动态样式实现更复杂的交互效果。
<template>
<transition name="slide">
<div class="ball" :style="{ left: x + 'px', top: y + 'px' }"></div>
</transition>
</template>
<script>
export default {
data() {
return {
x: 0,
y: 0,
};
},
mounted() {
setInterval(() => {
this.x = Math.random() * 300;
this.y = Math.random() * 300;
}, 1000);
},
};
</script>
<style>
.ball {
width: 30px;
height: 30px;
background-color: green;
border-radius: 50%;
position: absolute;
transition: all 0.5s ease;
}
.slide-enter-active, .slide-leave-active {
transition: all 0.5s;
}
</style>
关键点总结
- 动态绑定样式:通过 Vue 的
:style绑定小球的left和top实现位置变化。 - 动画控制:使用
requestAnimationFrame或setInterval更新坐标。 - 边界检测:在 JavaScript 中检查小球是否超出边界并反转方向。
- CSS 动画:通过
@keyframes或transition实现平滑效果。
根据需求选择合适的方法,动态绑定样式适合复杂逻辑,CSS 动画适合简单路径。





