效果图:
<a-table :dataSource="dataSource" :columns="columns" :pagination="false">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'td'">
<div style="cursor: pointer;" :draggable="true" @dragstart="dragstart(record, $event)" @dragenter="dragenter(record, $event)" @dragend="dragend(record, $event)">
<more-outlined />
</div>
</template>
</template>
</a-table>
一、替换位置的拖拽
const dataSource = ref([
{
key: '1',
name: 'a',
age: 1,
address: 1,
icon: ""
},
{
key: '2',
name: 'b',
age: 0,
address: 2,
icon: ""
},
{
key: '3',
name: 'c',
age: 0,
address: 2,
icon: ""
},
{
key: '4',
name: 'd',
age: 0,
address: 2,
icon: ""
},
])
const columns = ref([
{
title: '',
dataIndex: 'td',
key: 'td'
},
{
title: '名称',
dataIndex: 'name',
key: 'name',
}
])
const oldData = ref(null);
const newData = ref(null);
function dragstart(record, e) {
oldData.value = record
}
function dragenter(record, e) {
newData.value = record
}
function dragend(record, e) {
if (oldData.value !== newData.value) {
let oldIndex = dataSource.value.indexOf(oldData.value)
let newIndex = dataSource.value.indexOf(newData.value)
//将oldIndex下标的数据和newIndex下标的数据在dataSource.value的位置调换一下
dataSource.value.splice(oldIndex,1,newData.value);
dataSource.value.splice(newIndex,1,oldData.value);
}
}
二、插入位置的拖拽
const oldData = ref(null);
const newData = ref(null);
function dragstart(record, e) {
oldData.value = record;
}
function dragenter(record, e) {
newData.value = record;
}
function insertElementBottom(arr, index, element) {
arr.push(null); // 在数组末尾添加一个 null,用于存储被挤出的元素
for (let i = arr.length - 1; i > index; i--) {
arr[i] = arr[i - 1]; // 将元素向后移动一个位置
}
arr[index] = element; // 插入新元素
}
function insertElementTop(arr, index, element) {
arr.splice(index, 0, element); // 使用splice方法在指定位置插入元素
return arr;
}
function dragend(record, e) {
if (oldData.value !== newData.value) {
let oldIndex = tableData.value.indexOf(oldData.value);
let newIndex = tableData.value.indexOf(newData.value);
if (newIndex < oldIndex) {
tableData.value.splice(oldIndex, 1);
insertElementBottom(tableData.value, newIndex, oldData.value);
} else if (newIndex > oldIndex) {
tableData.value.splice(oldIndex, 1);
insertElementTop(tableData.value, newIndex, oldData.value);
}
}
}