代码中使用到的插件有sortablejs和lodash
指令参数:
- arg:排序字段
- value:vxe-table表格的实例对象
import Sortable from "sortablejs";
import { cloneDeep } from 'lodash'
const getOrderList = ({oldIndex,newIndex,tableData,field}) => {
const newList = cloneDeep(tableData)
if (oldIndex > newIndex) {
for(let index = newList.length; index > 0; index--) {
if (index < oldIndex && index >= newIndex) {
const curr = newList[index]
const prev = newList[index + 1]
newList[index] = cloneDeep(prev)
newList[index + 1] = cloneDeep(curr)
newList[index][field] = curr[field]
newList[index + 1][field] = prev[field]
}
}
} else if (oldIndex < newIndex) {
for(let index = 0; index < newList.length; index++) {
if (index > oldIndex && index <= newIndex) {
const curr = newList[index]
const next = newList[index - 1]
newList[index] = cloneDeep(next)
newList[index - 1] = cloneDeep(curr)
newList[index][field] = curr[field]
newList[index - 1][field] = next[field]
}
}
}
return newList
}
export const vSortable = (el,binding) => {
const {arg: field,value: xGrid} = binding
const tbody = el.querySelector(".vxe-table--body tbody")
if(!xGrid) return
setTimeout(() => {
let tableData = []
const column = xGrid.getColumnByField(field)
new Sortable(tbody,{
animation: 200,
handle: `[colid=${column.id}]`,
ghostClass: "sortable-ghost",
direction: "vertical",
onEnd: ({oldIndex,newIndex}) => {
const newList = getOrderList({oldIndex,newIndex,tableData,field})
xGrid.reloadData(newList)
},
onStart: () => {
tableData = xGrid.getTableData().tableData
},
})
})
}
示例
<vxe-grid v-sortable:sort="xGrid" ref="xGrid" v-bind="gridOptions" :data="data">
</vxe-grid>