Skip to content

Commit 1c9a0b3

Browse files
committed
feat(watch): support dot-delimited path in watch option
1 parent 5bfcad1 commit 1c9a0b3

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

packages/runtime-core/__tests__/apiOptions.spec.ts

+12-2
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ describe('api: options', () => {
113113
const spyB = jest.fn(returnThis)
114114
const spyC = jest.fn(returnThis)
115115
const spyD = jest.fn(returnThis)
116+
const spyE = jest.fn(returnThis)
116117

117118
let ctx: any
118119
const Comp = {
@@ -123,7 +124,10 @@ describe('api: options', () => {
123124
baz: {
124125
qux: 3
125126
},
126-
qux: 4
127+
qux: 4,
128+
dot: {
129+
path: 5
130+
}
127131
}
128132
},
129133
watch: {
@@ -137,7 +141,8 @@ describe('api: options', () => {
137141
},
138142
qux: {
139143
handler: 'onQuxChange'
140-
}
144+
},
145+
'dot.path': spyE
141146
},
142147
methods: {
143148
onFooChange: spyA,
@@ -175,6 +180,11 @@ describe('api: options', () => {
175180
await nextTick()
176181
expect(spyD).toHaveBeenCalledTimes(1)
177182
assertCall(spyD, 0, [5, 4])
183+
184+
ctx.dot.path++
185+
await nextTick()
186+
expect(spyE).toHaveBeenCalledTimes(1)
187+
assertCall(spyE, 0, [6, 5])
178188
})
179189

180190
test('watch array', async () => {

packages/runtime-core/src/componentOptions.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -816,7 +816,9 @@ function createWatcher(
816816
publicThis: ComponentPublicInstance,
817817
key: string
818818
) {
819-
const getter = () => (publicThis as any)[key]
819+
const getter = key.includes('.')
820+
? createPathGetter(publicThis, key)
821+
: () => (publicThis as any)[key]
820822
if (isString(raw)) {
821823
const handler = ctx[raw]
822824
if (isFunction(handler)) {
@@ -840,7 +842,18 @@ function createWatcher(
840842
}
841843
}
842844
} else if (__DEV__) {
843-
warn(`Invalid watch option: "${key}"`)
845+
warn(`Invalid watch option: "${key}"`, raw)
846+
}
847+
}
848+
849+
function createPathGetter(ctx: any, path: string) {
850+
const segments = path.split('.')
851+
return () => {
852+
let cur = ctx
853+
for (let i = 0; i < segments.length && cur; i++) {
854+
cur = cur[segments[i]]
855+
}
856+
return cur
844857
}
845858
}
846859

0 commit comments

Comments
 (0)