ElementUI+sortablejs实现列表拖拽功能
一、简介
SortableJS 是一个用于实现拖放排序功能的 JavaScript 库,可以帮助开发者轻松地实现拖拽元素重新排序的功能。以下是 SortableJS 的基本用法。
二、使用
2.1 安装 SortableJS
如果使用 npm,可以运行以下命令进行安装:
npm install sortablejs
2.2 安装 引入 SortableJS
在 HTML 文件中引入 SortableJS 的库文件:
import Sortable from 'sortablejs'
2.3 完整代码示例
<template>
<div>
<el-table :data="planTableData"
row-key="id">
<el-table-column prop="createTime"
label="时间"
width="180"></el-table-column>
<el-table-column prop="event"
label="事件"
width="180"></el-table-column>
<!-- 其他列 -->
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs'
import axios from 'axios' // 引入axios进行HTTP请求
export default {
name: 'PlanTableDraggable',
data () {
return {
planTableData: []
}
},
created () {
this.planTableData = [
{ id: 1, createTime: '2023-01-01', event: '事件1' },
{ id: 2, createTime: '2023-01-02', event: '事件2' },
{ id: 3, createTime: '2023-01-03', event: '事件3' }
// ...更多测试数据
]
},
mounted () {
this.$nextTick(() => {
const el = this.$el.querySelector('.el-table__body-wrapper tbody')
Sortable.create(el, {
onEnd: (event) => {
const { oldIndex, newIndex } = event
this.updateRowOrder(oldIndex, newIndex)
}
})
})
},
methods: {
updateRowOrder (oldIndex, newIndex) {
const movedItem = this.planTableData.splice(oldIndex, 1)[0]
this.planTableData.splice(newIndex, 0, movedItem)
this.updateOrderOnServer()
},
updateOrderOnServer () {
axios.post('/api/update-order', { newOrder: this.planTableData })
.then(response => {
console.log('Order updated:', response)
})
.catch(error => {
console.error('Error updating order:', error)
// 可能需要回滚操作
})
}
}
}
</script>