This commit is contained in:
linzhe 2025-06-19 00:14:11 +08:00 committed by GitHub
commit 601218f501
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 42 additions and 1 deletions

View File

@ -1,4 +1,4 @@
import { effect, isReactive, reactive, toRaw } from '../../src'
import { computed, effect, isReactive, reactive, ref, toRaw } from '../../src'
describe('reactivity/collections', () => {
function coverCollectionFn(collection: Set<any>, fnName: string) {
@ -459,5 +459,21 @@ describe('reactivity/collections', () => {
const result = set.add('a')
expect(result).toBe(set)
})
it('set with union in computed', () => {
const set1 = ref(new Set([1, 2, 3]))
const set2 = ref(new Set([2, 3, 4]))
// @ts-expect-error
const setSpy = vi.fn(() => set1.value.union(set2.value))
const c = computed(setSpy)
effect(() => c.value)
expect(setSpy).toHaveBeenCalledTimes(1)
set1.value.add(6)
expect(setSpy).toHaveBeenCalledTimes(2)
expect(c.value).toEqual(new Set([1, 2, 3, 4, 6]))
set2.value.add(7)
expect(setSpy).toHaveBeenCalledTimes(3)
expect(c.value).toEqual(new Set([1, 2, 3, 4, 6, 7]))
})
})
})

View File

@ -91,6 +91,18 @@ function createReadonlyMethod(type: TriggerOpTypes): Function {
}
}
function createSetProtoMethod(method: string) {
return function (this: SetTypes, value: unknown) {
value = toRaw(value)
const target = (this as any)[ReactiveFlags.RAW]
const rawTarget = toRaw(target)
const result = target[method](value)
track(rawTarget, TrackOpTypes.ITERATE, ITERATE_KEY)
track(value as any, TrackOpTypes.ITERATE, ITERATE_KEY)
return result
}
}
type Instrumentations = Record<string | symbol, Function | number>
function createInstrumentations(
@ -257,6 +269,19 @@ function createInstrumentations(
instrumentations[method] = createIterableMethod(method, readonly, shallow)
})
const setProtoMethods = [
'difference',
'intersection',
'isDisjointFrom',
'isSubsetOf',
'isSupersetOf',
'symmetricDifference',
'union',
] as const
setProtoMethods.forEach(method => {
instrumentations[method] = createSetProtoMethod(method)
})
return instrumentations
}