# vue3-ts-sortable拖拽排序
# 1.安装
安装SortableJS和@types/sortablejs
npm i SortableJS @types/sortablejs
# 2.导入使用
import Sortablejs from "sortablejs";
import type Sortable from "sortablejs";
interface Item {
id: number;
name: string;
}
const items = ref<Item[]>([
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
{ id: 3, name: "Item 3" },
{ id: 4, name: "Item 4" },
]);
const sortableList = ref<HTMLElement | null>(null);
let sortable: Sortable;
let sortableOrder: string[] = [];
const resetSort = () => {
sortable.sort(sortableOrder);
};
onMounted(() => {
if (!sortableList.value) return;
sortable = Sortablejs.create(sortableList.value, {
animation: 500,
delay: 400,
delayOnTouchOnly: true,
handle: ".item-li",
onEnd: evt => {
const { oldIndex = 0, newIndex = 0 } = evt;
if (oldIndex > newIndex) {
items.value.splice(newIndex, 0, items.value[oldIndex]);
items.value.splice(oldIndex + 1, 1);
} else {
items.value.splice(newIndex + 1, 0, items.value[oldIndex]);
items.value.splice(oldIndex, 1);
}
},
});
sortableOrder = sortable.toArray();
});