先看看效果
代碼
helper.js
export const data = [
{
key: "1",
name: "張三",
age: 32,
address: "西湖區湖底公園1號"
},
{
key: "2",
name: "胡彥祖",
age: 42,
address: "西湖區湖底公園2號"
},
{
key: "3",
name: "李四",
age: 22,
address: "西湖區湖底公園3號"
}
];
export const columns = [
{
title: "姓名",
dataIndex: "name",
key: "name"
},
{
title: "年齡",
dataIndex: "age",
key: "age"
},
{
title: "住址",
dataIndex: "address",
key: "address"
}
]
demo.vue
<template>
<div class="demo">
<a-table id="mytb" :dataSource="dataSource" :columns="columns" />
</div>
</template>
<script>
import { data, columns } from "./helper";
import { onMounted } from "@vue/runtime-core";
import Sortable from "sortablejs";
import { message } from "ant-design-vue";
export default {
setup() {
const dataSource = ref([]);
// 更新列表接口
const syncdataSource = () => {
const res = await Promise.resolve(data);
dataSource.value = res;
};
//初始化表格拖動
const initSortable = () => {
const mytb = document.querySelector("#mytb tbody");
new Sortable(mytb, {
handle: ".ant-table-row",
animation: 150,
ghostClass: "blue-background-class",
sort: true,
async onEnd({ newIndex, oldIndex }) {
const source = dataSource.value[oldIndex]; // 誰
const destination = dataSource.value[newIndex]; // 移動到哪兒
// 拖動后同步至stata
dataSource.value[newIndex] = source;
dataSource.value[oldIndex] = destination;
message.success('排序完成');
// // 執行接口更新拖動后的接口
// const parmas = {
// sourceId: source.id, //源話術id
// destinationId: destination.id, //目的話術id
// };
// try {
// const res = await api.sort(parmas);
// if (res.code === 0) {
// message.success(`移動成功`);
// } else {
// message.error(`移動失敗`);
// }
// } catch (e) {
// message.error(`移動失敗`);
// } finally {
// syncdataSource();
// }
},
});
};
onMounted(() => {
syncdataSource();
initSortable();
});
return { dataSource, columns };
},
};
</script>
<style scoped lang="less">
.demo {
width: 800px;
margin: auto;
margin-top: 20px;
}
</style>