- 安装sortable.js
npm install sortable.js
2.代码
<template>
<div ref="tableRef">
<el-table :data="dataList" :empty-text="'暂无数据'" stripe border>
<el-table-column prop="level" label="排序" width="120">
<template #default="{ row }">
<div class="flex items-center">
<span class="mr-sm">{{ row.level }}</span>
<el-icon class="drag-handle"><Sort /></el-icon>
</div>
</template>
</el-table-column>
<el-table-column prop="type" label="类型" min-width="120"> </el-table-column>
<el-table-column prop="name" label="名称" min-width="120"> </el-table-column>
</el-table>
</div>
</template>
<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';
import Sortable from 'sortablejs';
import { Sort } from '@element-plus/icons-vue';
const dataList = ref<any[]>([
{
level: '1',
type: '类型1',
name: '名称1',
},
{
level: '2',
type: '类型2',
name: '名称2',
},
{
level: '3',
type: '类型3',
name: '名称3',
},
{
level: '4',
type: '类型4',
name: '名称4',
},
]);
/**
* 是否可以拖拽
*/
function canDrag() {
const can = dataList.value.every((item) => {
return !item.isEdit;
});
return can;
}
function fastExtend(data: any) {
return JSON.parse(JSON.stringify(data));
}
const tableRef = ref();
onMounted(() => {
const tbody = tableRef.value.querySelector('.el-table__body-wrapper tbody');
if (tbody) {
Sortable.create(tbody, {
animation: 150,
handle: '.drag-handle',
onMove: () => {
console.log(canDrag());
return canDrag();
},
onEnd: ({ oldIndex, newIndex }: any) => {
if (!canDrag()) return;
if (oldIndex === undefined || newIndex === undefined) return;
const list = fastExtend(dataList.value);
dataList.value = [];
const currRow = list.splice(oldIndex, 1)[0];
let newArr = [...list.slice(0, newIndex), currRow, ...list.slice(newIndex)];
newArr.forEach((item, index) => {
item.level = index + 1 + '';
});
nextTick(() => {
dataList.value = newArr;
});
},
});
}
});
</script>
<style lang="scss" scoped>
.drag-handle {
cursor: move;
color: #666;
font-size: 16px;
&:hover {
color: #409eff;
}
}
</style>
3.效果图
69kcm-5xmh1.gif