vue实现列拖拽
Vue 实现列拖拽的方法
使用 Vue.Draggable 库
Vue.Draggable 是一个基于 Sortable.js 的 Vue 组件,适用于列表拖拽排序。安装方式如下:
npm install vuedraggable
基本用法示例:

<template>
<draggable v-model="list" @end="onDragEnd">
<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: {
onDragEnd() {
console.log('拖拽完成')
}
}
}
</script>
使用原生 HTML5 Drag and Drop API
HTML5 提供了原生的拖拽 API,可以在 Vue 中直接使用:
<template>
<div
v-for="item in list"
:key="item.id"
draggable="true"
@dragstart="handleDragStart($event, item)"
@dragover.prevent
@drop="handleDrop($event, item)"
>
{{ item.name }}
</div>
</template>
<script>
export default {
data() {
return {
list: [...],
draggedItem: null
}
},
methods: {
handleDragStart(e, item) {
this.draggedItem = item
e.dataTransfer.effectAllowed = 'move'
},
handleDrop(e, targetItem) {
const draggedIndex = this.list.indexOf(this.draggedItem)
const targetIndex = this.list.indexOf(targetItem)
this.list.splice(draggedIndex, 1)
this.list.splice(targetIndex, 0, this.draggedItem)
}
}
}
</script>
表格列拖拽实现
对于表格列的拖拽排序,可以结合上述方法:

<template>
<table>
<thead>
<tr>
<th
v-for="(col, index) in columns"
:key="col.key"
draggable="true"
@dragstart="handleDragStart($event, index)"
@dragover.prevent
@drop="handleDrop($event, index)"
>
{{ col.title }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="row in data" :key="row.id">
<td v-for="col in columns" :key="col.key">
{{ row[col.key] }}
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
columns: [
{ key: 'name', title: 'Name' },
{ key: 'age', title: 'Age' }
],
data: [...],
draggedColIndex: null
}
},
methods: {
handleDragStart(e, index) {
this.draggedColIndex = index
e.dataTransfer.effectAllowed = 'move'
},
handleDrop(e, targetIndex) {
const cols = [...this.columns]
const draggedCol = cols[this.draggedColIndex]
cols.splice(this.draggedColIndex, 1)
cols.splice(targetIndex, 0, draggedCol)
this.columns = cols
}
}
}
</script>
注意事项
拖拽功能需要考虑浏览器兼容性问题,特别是移动端支持情况。对于复杂场景,建议使用成熟的库如 Vue.Draggable 或 Sortable.js。
拖拽状态需要合理管理,避免直接修改 props 数据,应该通过事件通知父组件。
性能优化方面,对于大数据量的列表,应该使用虚拟滚动等技术配合拖拽功能。






