import { diffArrayChange } from "@/utils"; import { ref, Ref, watch } from "vue"; export const useSelects = (items: Ref) => { const selects = ref([]); const updateSelect = (item: T, select: boolean) => { const ndx = selects.value.findIndex((s) => s.id === item.id); if (select) { ~ndx || selects.value.push(item as any); } else { ~ndx && selects.value.splice(ndx, 1); } }; const updateSelectId = (id: any, select: boolean) => { const item = items.value.find((s) => s.id === id); item && updateSelect(item, select); }; const oldItems: T[] = []; watch( items, (items) => { const { added, deleted } = diffArrayChange( items.map((item) => item.id), oldItems.map((item) => item.id) ); added.forEach((id) => updateSelectId(id, true)); deleted.forEach((id) => updateSelectId(id, false)); oldItems.length = 0; oldItems.push(...items); }, { deep: true } ); return { selects, updateSelect, updateSelectId, }; };