vue 实现div拖拽
实现 div 拖拽的基本思路
在 Vue 中实现 div 拖拽功能,可以通过监听鼠标事件(mousedown、mousemove、mouseup)来实现。核心逻辑是记录拖拽起始位置,计算位移并更新 div 的位置。
使用原生事件实现拖拽
-
模板部分
在模板中绑定事件,并通过style动态设置 div 的位置:<template> <div class="draggable" @mousedown="startDrag" @mousemove="onDrag" @mouseup="stopDrag" @mouseleave="stopDrag" :style="{ left: position.x + 'px', top: position.y + 'px' }" > 可拖拽的 div </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, }; }, onDrag(e) { if (!this.isDragging) return; this.position = { x: e.clientX - this.startPos.x, y: e.clientY - this.startPos.y, }; }, stopDrag() { this.isDragging = false; }, }, }; </script> -
样式部分
确保 div 可以自由移动:<style> .draggable { position: absolute; cursor: grab; user-select: none; } </style>
使用第三方库(如 vuedraggable)
如果需要更复杂的拖拽功能(如列表排序),可以使用 vuedraggable 库:

-
安装库
npm install vuedraggable -
实现列表拖拽
<template> <draggable v-model="list" @start="onStart" @end="onEnd"> <div v-for="item in list" :key="item.id"> {{ item.name }} </div> </draggable> </template> <script> import draggable from "vuedraggable"; export default { components: { draggable }, data() { return { list: [ { id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }, ], }; }, methods: { onStart() { console.log("拖拽开始"); }, onEnd() { console.log("拖拽结束"); }, }, }; </script>
注意事项
- 拖拽性能优化:避免频繁触发
mousemove事件,可以使用防抖(debounce)或节流(throttle)。 - 边界检查:防止 div 拖拽超出可视区域。
- 移动端适配:如果需要支持触摸屏,需监听
touchstart、touchmove、touchend事件。
通过以上方法,可以灵活实现 Vue 中的 div 拖拽功能。






