vue实现左右拖拽
实现左右拖拽功能
在Vue中实现左右拖拽功能可以通过监听鼠标事件和使用CSS变换来实现。以下是具体的实现方法。
使用鼠标事件监听
通过监听mousedown、mousemove和mouseup事件来跟踪拖拽行为。
<template>
<div
class="draggable"
@mousedown="startDrag"
@mousemove="onDrag"
@mouseup="stopDrag"
@mouseleave="stopDrag"
:style="{ left: position.x + 'px', top: position.y + 'px' }"
>
拖拽我
</div>
</template>
<script>
export default {
data() {
return {
isDragging: false,
startPos: { x: 0, y: 0 },
position: { 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>
<style>
.draggable {
position: absolute;
width: 100px;
height: 100px;
background-color: #42b983;
cursor: move;
user-select: none;
}
</style>
使用第三方库
对于更复杂的拖拽需求,可以使用第三方库如vuedraggable或sortablejs。
安装vuedraggable:
npm install vuedraggable
示例代码:
<template>
<div>
<draggable v-model="list" @start="drag=true" @end="drag=false">
<div v-for="element in list" :key="element.id">
{{ element.name }}
</div>
</draggable>
</div>
</template>
<script>
import draggable from 'vuedraggable';
export default {
components: { draggable },
data() {
return {
list: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
};
}
};
</script>
使用CSS拖拽
对于简单的拖拽效果,可以使用CSS的drag属性,但兼容性较差。
<template>
<div draggable="true" @dragstart="handleDragStart">
拖拽我
</div>
</template>
<script>
export default {
methods: {
handleDragStart(e) {
e.dataTransfer.setData('text/plain', '拖拽内容');
}
}
};
</script>
注意事项
确保拖拽元素具有position: absolute或position: relative样式,以便正确计算位置。
拖拽过程中避免触发文本选择,可以通过CSS设置user-select: none。

对于移动端支持,需要额外处理touchstart、touchmove和touchend事件。






