Skip to content

Commit

Permalink
fix(reactivity): track hasOwnProperty
Browse files Browse the repository at this point in the history
fix #2619
close #2621
  • Loading branch information
yyx990803 committed Nov 14, 2022
1 parent ce363e5 commit 588bd44
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
26 changes: 26 additions & 0 deletions packages/reactivity/__tests__/effect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -964,5 +964,31 @@ describe('reactivity/effect', () => {
m.set(key, 2)
expect(fnSpy).toHaveBeenCalledTimes(2)
})

test('should track hasOwnProperty', () => {
const obj: any = reactive({})
let has = false
const fnSpy = jest.fn()

effect(() => {
fnSpy()
has = obj.hasOwnProperty('foo')
})
expect(fnSpy).toHaveBeenCalledTimes(1)
expect(has).toBe(false)

obj.foo = 1
expect(fnSpy).toHaveBeenCalledTimes(2)
expect(has).toBe(true)

delete obj.foo
expect(fnSpy).toHaveBeenCalledTimes(3)
expect(has).toBe(false)

// should not trigger on unrelated key
obj.bar = 2
expect(fnSpy).toHaveBeenCalledTimes(3)
expect(has).toBe(false)
})
})
})
16 changes: 14 additions & 2 deletions packages/reactivity/src/baseHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ function createArrayInstrumentations() {
return instrumentations
}

function hasOwnProperty(key: string) {
// @ts-ignore
const obj = toRaw(this)
track(obj, TrackOpTypes.HAS, key)
return obj.hasOwnProperty(key)
}

function createGetter(isReadonly = false, shallow = false) {
return function get(target: Target, key: string | symbol, receiver: object) {
if (key === ReactiveFlags.IS_REACTIVE) {
Expand All @@ -110,8 +117,13 @@ function createGetter(isReadonly = false, shallow = false) {

const targetIsArray = isArray(target)

if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
return Reflect.get(arrayInstrumentations, key, receiver)
if (!isReadonly) {
if (targetIsArray && hasOwn(arrayInstrumentations, key)) {
return Reflect.get(arrayInstrumentations, key, receiver)
}
if (key === 'hasOwnProperty') {
return hasOwnProperty
}
}

const res = Reflect.get(target, key, receiver)
Expand Down

0 comments on commit 588bd44

Please sign in to comment.