- Sortable.js是一款优秀的js拖拽库,支持ie9及以上版本ie浏览器和现代浏览器,也可以运行在移动触摸设备中。不依赖jQuery。支持 Meteor、AngularJS、React、Vue、Knockout框架和任何CSS库,如Bootstrap、Element UI。你可以用来拖拽div、table等元素。
-
Sortable.js下载
npm 安装方式
npm install sortablejs --save
-
Sortable.js使用
-
在js中导入
import Sortable from 'sortablejs' -
表格加上 row-key 和 ref
<el-table ref="table" row-key="id" :data="tableData" >
( 注:row-key 写不正确可能会出现一些BUG,row-key需要是唯一的)
-
具体实现
dragSort() {
const el = this.$refs.table.$el.querySelectorAll(
'.el-table__body-wrapper > table > tbody'
)[0]
this.sortable = Sortable.create(el, {
ghostClass: 'sortable-ghost',
setData: function(dataTransfer) {
dataTransfer.setData('Text', '')
},
onEnd: async e => {
// e.oldIndex为拖动一行原来的位置,e.newIndex为拖动后新的位置
const targetRow = this.tableData.splice(e.oldIndex, 1)[0] // 拖拽后的行
console.log(targetRow)
this.tableData.splice(e.newIndex, 0, targetRow) // 得到拖拽后的数组
let sortData = this.tableData.map((item, index) => {
item.index_sort = index
return {
id: item.id,
index_sort: item.index_sort
}
})
const res = await this.$http.post(`api/countries/sort`, {
sort_data: sortData
})
if (res.ret) {
this.$notify({
title: this.$t('success'),
message: res.msg,
type: 'success'
})
}
}
})
}