【VUE】ant design vue实现表格table上下拖拽排序
适合版本:ant design vue 1.7.8
实现效果:
代码:
<template>
<div class="table-container">
<a-table
:columns="columns"
:dataSource="tableData"
:rowKey="record => record.id"
:rowClassName="getRowClassName"
>
<template v-slot:action="text,record">
<a-button type="primary" icon="drag" @mousedown="startDrag(record, $event)"></a-button>
</template>
</a-table>
</div>
</template>
<script>
import { Table, Button } from 'ant-design-vue';
export default {
components: {
'a-table': Table,
'a-button': Button
},
data() {
return {
tableData: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
],
columns: [
{ title: 'ID', dataIndex: 'id', key: 'id' },
{ title: 'Name', dataIndex: 'name', key: 'name' },
{
title: 'Action',
key: 'action',
scopedSlots: { customRender: 'action' }
}
],
draggingItem: null,
draggingIndex: -1
};
},
methods: {
getRowClassName(record, index) {
return index === this.draggingIndex ? 'dragging-row' : '';
},
startDrag(record, event) {
this.draggingItem = record;
this.draggingIndex = this.tableData.findIndex(item => item.id === record.id);
document.addEventListener('mousemove', this.onDrag);
document.addEventListener('mouseup', this.stopDrag);
},
onDrag(event) {
const mouseY = event.clientY;
const tableRows = document.querySelectorAll('.ant-table-row');
let targetIndex = -1;
tableRows.forEach((row, index) => {
const rect = row.getBoundingClientRect();
if (mouseY >= rect.top && mouseY <= rect.bottom) {
targetIndex = index;
}
});
if (targetIndex !== -1 && targetIndex !== this.draggingIndex) {
const [draggedItem] = this.tableData.splice(this.draggingIndex, 1);
this.tableData.splice(targetIndex, 0, draggedItem);
this.draggingIndex = targetIndex;
}
},
stopDrag() {
document.removeEventListener('mousemove', this.onDrag);
document.removeEventListener('mouseup', this.stopDrag);
this.draggingItem = null;
this.draggingIndex = -1;
}
}
};
</script>
<style>
.dragging-row {
background-color: #f0f0f0;
cursor: grabbing;
}
</style>