import { watchEffect, nextTick, effectScope } from "vue"; import { diffArrayChange } from './diff' import type { EffectScope } from 'vue' // 一次监听 export const onlyWatchEffect: typeof watchEffect = (cb, options) => { const stopWatch = watchEffect((...args) => { cb(...args); nextTick(stopWatch); }, options); return stopWatch; }; export const shallowWatchArray = ( getItems: () => T, cb: (newItems: T, oldItems: T) => void ) => { let oldItems = [] as unknown as T watchEffect(() => { const newItems = getItems() cb(newItems, oldItems) oldItems = [...newItems] as T }) } export const arrayChildEffectScope = ( getItems: () => T, cb: (item: T[number]) => void ) => { const scopes = new WeakMap() shallowWatchArray(getItems, (newItems, oldItems) => { const { added, deleted } = diffArrayChange(newItems, oldItems) for (const addItem of added) { const scope = effectScope() scope.run(() => { cb(addItem) }) scopes.set(addItem, scope) } for (const delItem of deleted) { scopes.get(delItem)?.stop() } }) }