File tree 2 files changed +33
-2
lines changed
2 files changed +33
-2
lines changed Original file line number Diff line number Diff line change @@ -27,6 +27,33 @@ describe('api: watch', () => {
27
27
expect ( dummy ) . toBe ( 1 )
28
28
} )
29
29
30
+ it ( 'triggers when initial value is null' , async ( ) => {
31
+ const state = ref ( null )
32
+ const spy = jest . fn ( )
33
+ watch ( ( ) => state . value , spy )
34
+ await nextTick ( )
35
+ expect ( spy ) . toHaveBeenCalled ( )
36
+ } )
37
+
38
+ it ( 'triggers when initial value is undefined' , async ( ) => {
39
+ const state = ref ( )
40
+ const spy = jest . fn ( )
41
+ watch ( ( ) => state . value , spy )
42
+ await nextTick ( )
43
+ expect ( spy ) . toHaveBeenCalled ( )
44
+ state . value = 3
45
+ await nextTick ( )
46
+ expect ( spy ) . toHaveBeenCalledTimes ( 2 )
47
+ // testing if undefined can trigger the watcher
48
+ state . value = undefined
49
+ await nextTick ( )
50
+ expect ( spy ) . toHaveBeenCalledTimes ( 3 )
51
+ // it shouldn't trigger if the same value is set
52
+ state . value = undefined
53
+ await nextTick ( )
54
+ expect ( spy ) . toHaveBeenCalledTimes ( 3 )
55
+ } )
56
+
30
57
it ( 'watching single source: getter' , async ( ) => {
31
58
const state = reactive ( { count : 0 } )
32
59
let dummy
Original file line number Diff line number Diff line change @@ -61,6 +61,9 @@ export type StopHandle = () => void
61
61
62
62
const invoke = ( fn : Function ) => fn ( )
63
63
64
+ // initial value for watchers to trigger on undefined initial values
65
+ const INITIAL_WATCHER_VALUE = { }
66
+
64
67
// overload #1: simple effect
65
68
export function watch ( effect : WatchEffect , options ?: WatchOptions ) : StopHandle
66
69
@@ -153,7 +156,7 @@ function doWatch(
153
156
}
154
157
}
155
158
156
- let oldValue = isArray ( source ) ? [ ] : undefined
159
+ let oldValue = isArray ( source ) ? [ ] : INITIAL_WATCHER_VALUE
157
160
const applyCb = cb
158
161
? ( ) => {
159
162
if ( instance && instance . isUnmounted ) {
@@ -167,7 +170,8 @@ function doWatch(
167
170
}
168
171
callWithAsyncErrorHandling ( cb , instance , ErrorCodes . WATCH_CALLBACK , [
169
172
newValue ,
170
- oldValue ,
173
+ // pass undefined as the old value when it's changed for the first time
174
+ oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue ,
171
175
registerCleanup
172
176
] )
173
177
oldValue = newValue
You can’t perform that action at this time.
0 commit comments