以sortablejs为例
首先安装sortablejs
npm install sortablejs
导入
import Sortable from 'sortablejs';
Sortable使用
const setSort = () => {
if (tableRef.value) {
const el = tableRef.value?.$el.querySelector('.n-data-table-tbody');
Sortable.create(el, {
onEnd: (evt: any) => {
const targetRow = listData.value.splice(evt.oldIndex, 1)[0];
listData.value.splice(evt.newIndex, 0, targetRow);
},
});
}
};
onMounted方法中调用
onMounted(() => {
setSort();
});
例:
<template>
<n-data-table
ref="tableRef"
:data="listData"
:row-key="(row) => row?.id"
:bordered="false"
:single-line="true"
:columns="columns"
size="small"
></n-data-table>
</template>
<script lang="tsx" setup>
import { ref, h, onMounted } from 'vue';
import { NIcon } from 'naive-ui';
import { MenuOutlined } from '@vicons/antd';
import Sortable from 'sortablejs';
const tableRef = ref();
const listData = ref([{ id:0,adjustItemName: '213' }, { id:1,adjustItemName: '213000' }]);
const columns: any = [
{
title: '排序',
render() {
return h(NIcon, {
size: '14',
depth: 1,
component: MenuOutlined,
});
},
},
{
title: '名称',
key: 'adjustItemName',
},
{
title: '字段类型',
key: 'itemType',
render(row) {
return row.itemType?.label;
},
},
{
title: '操作人',
key: 'updateUser',
},
{
title: '上次更改时间',
key: 'updateTime',
},
];
const setSort = () => {
if (tableRef.value) {
const el = tableRef.value?.$el.querySelector('.n-data-table-tbody');
Sortable.create(el, {
onEnd: (evt: any) => {
const targetRow = listData.value.splice(evt.oldIndex, 1)[0];
listData.value.splice(evt.newIndex, 0, targetRow);
},
});
}
};
onMounted(() => {
setSort();
});
</script>