vue实现元素移动效果
使用 CSS Transition 实现基础移动
在 Vue 中可以通过数据绑定结合 CSS transition 实现平滑移动效果。定义数据属性控制元素位置,通过修改数据触发动画。

<template>
<div
class="move-box"
:style="{ transform: `translate(${x}px, ${y}px)` }"
@click="moveRandom"
></div>
</template>
<script>
export default {
data() {
return {
x: 0,
y: 0
}
},
methods: {
moveRandom() {
this.x = Math.floor(Math.random() * 300)
this.y = Math.floor(Math.random() * 300)
}
}
}
</script>
<style>
.move-box {
width: 100px;
height: 100px;
background-color: #42b983;
transition: transform 0.5s ease;
}
</style>
使用 Vue Transition 组件
Vue 内置的 <transition> 组件可以实现更复杂的入场/离场动画效果,配合 v-if 或 v-show 控制元素显示状态。

<template>
<button @click="show = !show">Toggle</button>
<transition name="slide">
<div v-if="show" class="box">滑动元素</div>
</transition>
</template>
<script>
export default {
data() {
return {
show: true
}
}
}
</script>
<style>
.box {
width: 100px;
height: 100px;
background: #ff7043;
}
.slide-enter-active, .slide-leave-active {
transition: all 0.5s;
}
.slide-enter, .slide-leave-to {
transform: translateX(100px);
opacity: 0;
}
</style>
使用 GSAP 实现高级动画
对于需要复杂时间轴控制的动画,可以使用 GSAP 动画库。安装 GSAP 后创建精细的运动轨迹。
npm install gsap
<template>
<div ref="box" class="gsap-box"></div>
<button @click="animate">开始动画</button>
</template>
<script>
import { gsap } from 'gsap'
export default {
methods: {
animate() {
gsap.to(this.$refs.box, {
x: 200,
y: 100,
duration: 1,
rotation: 360,
ease: "bounce.out"
})
}
}
}
</script>
<style>
.gsap-box {
width: 50px;
height: 50px;
background: #4fc08d;
margin: 20px;
}
</style>
拖拽移动实现
通过添加拖拽事件处理实现元素自由移动,适合需要用户交互的场景。
<template>
<div
class="draggable"
ref="dragEl"
@mousedown="startDrag"
:style="{ left: pos.x + 'px', top: pos.y + 'px' }"
>拖拽我</div>
</template>
<script>
export default {
data() {
return {
pos: { x: 0, y: 0 },
dragging: false,
startPos: { x: 0, y: 0 }
}
},
methods: {
startDrag(e) {
this.dragging = true
this.startPos = {
x: e.clientX - this.pos.x,
y: e.clientY - this.pos.y
}
document.addEventListener('mousemove', this.onDrag)
document.addEventListener('mouseup', this.stopDrag)
},
onDrag(e) {
if (this.dragging) {
this.pos = {
x: e.clientX - this.startPos.x,
y: e.clientY - this.startPos.y
}
}
},
stopDrag() {
this.dragging = false
document.removeEventListener('mousemove', this.onDrag)
document.removeEventListener('mouseup', this.stopDrag)
}
}
}
</script>
<style>
.draggable {
position: absolute;
width: 100px;
height: 100px;
background: #647eff;
cursor: move;
user-select: none;
}
</style>






