vue实现移动效果
使用 CSS 过渡实现移动效果
在 Vue 中,可以通过 v-bind:class 或 v-bind:style 结合 CSS 过渡实现移动效果。定义一个 CSS 类,包含 transition 属性和目标样式(如 transform: translateX())。通过 Vue 的数据绑定动态切换类名或样式。
<template>
<div
class="box"
:class="{ 'move-right': isMoved }"
@click="isMoved = !isMoved"
></div>
</template>
<script>
export default {
data() {
return {
isMoved: false
};
}
};
</script>
<style>
.box {
width: 100px;
height: 100px;
background: red;
transition: transform 0.5s ease;
}
.move-right {
transform: translateX(100px);
}
</style>
使用 Vue 的 <transition> 组件
Vue 内置的 <transition> 组件可以为元素添加进入/离开的过渡效果。结合 CSS 动画或第三方动画库(如 Animate.css)实现更复杂的移动效果。

<template>
<button @click="show = !show">Toggle</button>
<transition name="slide">
<div v-if="show" class="item">滑动内容</div>
</transition>
</template>
<script>
export default {
data() {
return {
show: false
};
}
};
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.5s;
}
.slide-enter-from, .slide-leave-to {
transform: translateX(100%);
}
.item {
width: 200px;
height: 50px;
background: blue;
}
</style>
使用 JavaScript 钩子与 GSAP
通过 Vue 的过渡 JavaScript 钩子(如 enter 和 leave)结合 GSAP 等动画库实现精细控制。

<template>
<button @click="show = !show">Toggle</button>
<transition
@enter="enterAnimation"
@leave="leaveAnimation"
>
<div v-if="show" class="item">GSAP 动画</div>
</transition>
</template>
<script>
import gsap from 'gsap';
export default {
data() {
return {
show: false
};
},
methods: {
enterAnimation(el, done) {
gsap.from(el, {
x: 100,
opacity: 0,
duration: 0.5,
onComplete: done
});
},
leaveAnimation(el, done) {
gsap.to(el, {
x: -100,
opacity: 0,
duration: 0.5,
onComplete: done
});
}
}
};
</script>
动态绑定样式实现实时移动
通过监听事件(如拖拽或滚动)动态计算位置,并绑定到元素的 style 属性。
<template>
<div
class="draggable"
:style="{ transform: `translate(${x}px, ${y}px)` }"
@mousedown="startDrag"
>拖拽我</div>
</template>
<script>
export default {
data() {
return {
x: 0,
y: 0,
isDragging: false
};
},
methods: {
startDrag(e) {
this.isDragging = true;
document.addEventListener('mousemove', this.drag);
document.addEventListener('mouseup', this.stopDrag);
},
drag(e) {
if (this.isDragging) {
this.x = e.clientX;
this.y = e.clientY;
}
},
stopDrag() {
this.isDragging = false;
document.removeEventListener('mousemove', this.drag);
}
}
};
</script>
使用第三方组件(如 vue-draggable)
对于复杂交互(如列表排序拖拽),可直接使用第三方库 vue-draggable 实现移动效果。
<template>
<draggable v-model="list" @end="onDragEnd">
<div v-for="item in list" :key="item.id">{{ item.text }}</div>
</draggable>
</template>
<script>
import draggable from 'vuedraggable';
export default {
components: { draggable },
data() {
return {
list: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
]
};
},
methods: {
onDragEnd() {
console.log('拖动结束');
}
}
};
</script>






