Skip to content

Commit 588bd44

Browse files
committed
fix(reactivity): track hasOwnProperty
fix#2619close#2621
1 parent ce363e5 commit 588bd44

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

‎packages/reactivity/__tests__/effect.spec.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -964,5 +964,31 @@ describe('reactivity/effect', () =>{
964964
m.set(key,2)
965965
expect(fnSpy).toHaveBeenCalledTimes(2)
966966
})
967+
968+
test('should track hasOwnProperty',()=>{
969+
constobj: any=reactive({})
970+
lethas=false
971+
constfnSpy=jest.fn()
972+
973+
effect(()=>{
974+
fnSpy()
975+
has=obj.hasOwnProperty('foo')
976+
})
977+
expect(fnSpy).toHaveBeenCalledTimes(1)
978+
expect(has).toBe(false)
979+
980+
obj.foo=1
981+
expect(fnSpy).toHaveBeenCalledTimes(2)
982+
expect(has).toBe(true)
983+
984+
deleteobj.foo
985+
expect(fnSpy).toHaveBeenCalledTimes(3)
986+
expect(has).toBe(false)
987+
988+
// should not trigger on unrelated key
989+
obj.bar=2
990+
expect(fnSpy).toHaveBeenCalledTimes(3)
991+
expect(has).toBe(false)
992+
})
967993
})
968994
})

‎packages/reactivity/src/baseHandlers.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,13 @@ function createArrayInstrumentations(){
8585
returninstrumentations
8686
}
8787

88+
functionhasOwnProperty(key: string){
89+
// @ts-ignore
90+
constobj=toRaw(this)
91+
track(obj,TrackOpTypes.HAS,key)
92+
returnobj.hasOwnProperty(key)
93+
}
94+
8895
functioncreateGetter(isReadonly=false,shallow=false){
8996
returnfunctionget(target: Target,key: string|symbol,receiver: object){
9097
if(key===ReactiveFlags.IS_REACTIVE){
@@ -110,8 +117,13 @@ function createGetter(isReadonly = false, shallow = false){
110117

111118
consttargetIsArray=isArray(target)
112119

113-
if(!isReadonly&&targetIsArray&&hasOwn(arrayInstrumentations,key)){
114-
returnReflect.get(arrayInstrumentations,key,receiver)
120+
if(!isReadonly){
121+
if(targetIsArray&&hasOwn(arrayInstrumentations,key)){
122+
returnReflect.get(arrayInstrumentations,key,receiver)
123+
}
124+
if(key==='hasOwnProperty'){
125+
returnhasOwnProperty
126+
}
115127
}
116128

117129
constres=Reflect.get(target,key,receiver)

0 commit comments

Comments
(0)