vue实现盒子拖拽
实现盒子拖拽的基本思路
在Vue中实现盒子拖拽功能,可以通过监听鼠标事件(mousedown、mousemove、mouseup)来实现。核心逻辑是记录拖拽起始位置,计算位移差值,并更新盒子的位置。
基础实现代码示例
<template>
<div
class="draggable-box"
ref="box"
:style="{ left: position.x + 'px', top: position.y + 'px' }"
@mousedown="startDrag"
>
拖拽我
</div>
</template>
<script>
export default {
data() {
return {
position: { x: 0, y: 0 },
isDragging: false,
startPos: { x: 0, y: 0 }
};
},
methods: {
startDrag(e) {
this.isDragging = true;
this.startPos = {
x: e.clientX - this.position.x,
y: e.clientY - this.position.y
};
document.addEventListener('mousemove', this.onDrag);
document.addEventListener('mouseup', this.stopDrag);
},
onDrag(e) {
if (!this.isDragging) return;
this.position = {
x: e.clientX - this.startPos.x,
y: e.clientY - this.startPos.y
};
},
stopDrag() {
this.isDragging = false;
document.removeEventListener('mousemove', this.onDrag);
document.removeEventListener('mouseup', this.stopDrag);
}
}
};
</script>
<style>
.draggable-box {
position: absolute;
width: 100px;
height: 100px;
background-color: #42b983;
cursor: move;
display: flex;
align-items: center;
justify-content: center;
color: white;
}
</style>
优化拖拽性能
为避免频繁触发mousemove事件导致性能问题,可以使用requestAnimationFrame优化:

onDrag(e) {
if (!this.isDragging) return;
requestAnimationFrame(() => {
this.position = {
x: e.clientX - this.startPos.x,
y: e.clientY - this.startPos.y
};
});
}
支持触摸设备
为兼容移动端触摸事件,需添加touchstart、touchmove和touchend事件:

<div
@mousedown="startDrag"
@touchstart="startDrag"
></div>
startDrag(e) {
const clientX = e.clientX || e.touches[0].clientX;
const clientY = e.clientY || e.touches[0].clientY;
// 其余逻辑不变
}
使用第三方库
若需更复杂的功能(如拖拽排序、边界限制),推荐使用以下库:
vuedraggable:基于Sortable.js的Vue拖拽组件interact.js:轻量级拖拽库,支持手势和惯性
边界限制示例
限制拖拽范围在父容器内:
onDrag(e) {
if (!this.isDragging) return;
const parentRect = this.$refs.box.parentElement.getBoundingClientRect();
const boxWidth = this.$refs.box.offsetWidth;
const boxHeight = this.$refs.box.offsetHeight;
let x = e.clientX - this.startPos.x;
let y = e.clientY - this.startPos.y;
x = Math.max(0, Math.min(x, parentRect.width - boxWidth));
y = Math.max(0, Math.min(y, parentRect.height - boxHeight));
this.position = { x, y };
}






