123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- 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 = <T extends any[]>(
- 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 = <T extends any[]>(
- getItems: () => T,
- cb: (item: T[number]) => void
- ) => {
- const scopes = new WeakMap<T, EffectScope>()
- 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()
- }
- })
- }
|