使用sortablejs+antdv进行拖到排序

发布于 16 天前 前端 最后更新于 14 天前


安装sortablejs npm i sortablejs

vue代码

<Table
  ref="zjTableRef"
  :dataSource="dataSource"
  :columns="columns"
  row-key="id"
></Table>

js代码

const zjTableRef = ref()
const tbody = zjTableRef.value?.$el?.querySelector(".ant-table-tbody");
if (!tbody) return;

sortableInstance.value = Sortable.create(tbody, {
  animation: 150,
  handle: ".ant-table-row",
  onEnd: ({ oldIndex, newIndex }) => {
    if (oldIndex === newIndex) return;
    // **调整 tableData 的顺序**
    const [movedItem] = dataSource.value.splice(oldIndex, 1); // 移除拖拽的元素
    dataSource.value.splice(newIndex, 0, movedItem); // 插入到新的位置
    dataSource.value = [...dataSource.value];
  },
});