<template>
<a-table :columns="columns" :data-source="dataSource" bordered></a-table>
</template>
<script>
import Sortable from 'sortablejs'
import { defineComponent, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
const data = [];
for (let i = 0; i < 100; i++) {
data.push({
key: i.toString(),
name: `Edrward ${i}`,
age: 32,
address: `London Park no. ${i}`,
operation: i
});
}
export default defineComponent({
setup() {
const columns = ref([{
title: 'name',
dataIndex: 'name',
width: '25%',
}, {
title: 'age',
dataIndex: 'age',
width: '15%',
}, {
title: 'address',
dataIndex: 'address',
width: '40%',
}, {
title: 'operation',
dataIndex: 'operation',
}]);
const dataSource = ref(data);
onMounted(() => {
columnDrop();
rowDrop();
})
const columnDrop = () => {
const wrapperTr = document.querySelector('.ant-table-thead tr');
Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
// onEnd: evt => {
// const oldItem = columns.value[evt.oldIndex]
// columns.value.splice(evt.oldIndex, 1)
// columns.value.splice(evt.newIndex, 0, oldItem)
// }
onEnd: evt => {
const oldItem = columns.value[evt.oldIndex];
columns.value.splice(evt.oldIndex, 1);
columns.value.splice(evt.newIndex, 0, oldItem);
// 不能跟第一列置换位置
if (evt.newIndex == 0) {
message.info('不能跟第一列置换位置。')
const oldItem = columns.value[evt.newIndex];
columns.value.splice(evt.newIndex, 1);
columns.value.splice(evt.oldIndex, 0, oldItem);
// 复原拖拽之前的 dom
const tagName = evt.item.tagName;
const items = evt.from.getElementsByTagName(tagName);
if (evt.oldIndex > evt.newIndex) {
evt.from.insertBefore(evt.item, items[evt.oldIndex + 1]);
} else {
evt.from.insertBefore(evt.item, items[evt.oldIndex]);
}
}
}
})
}
const rowDrop = () => {
const wrapperTr = document.querySelector('.ant-table-tbody');
Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
onEnd: evt => {
const currRow = dataSource.value.splice(evt.oldIndex, 1)[0];
dataSource.value.splice(evt.newIndex, 0, currRow);
}
})
}
return {
dataSource,
columns,
};
},
});
</script>
<style scoped>
.editable-row-operations a {
margin-right: 8px;
}
</style>
antdesign表格使用Sortable进行行列拖拽
最新推荐文章于 2024-11-19 16:16:36 发布