Skip to content

Commit

Permalink
fix(watch): allow handler to be a string
Browse files Browse the repository at this point in the history
Closes #1774
  • Loading branch information
posva committed Aug 4, 2020
1 parent 11ed210 commit 4fe36d5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
15 changes: 13 additions & 2 deletions packages/runtime-core/__tests__/apiOptions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ describe('api: options', () => {
const spyA = jest.fn(returnThis)
const spyB = jest.fn(returnThis)
const spyC = jest.fn(returnThis)
const spyD = jest.fn(returnThis)

let ctx: any
const Comp = {
Expand All @@ -121,7 +122,8 @@ describe('api: options', () => {
bar: 2,
baz: {
qux: 3
}
},
qux: 4
}
},
watch: {
Expand All @@ -132,10 +134,14 @@ describe('api: options', () => {
baz: {
handler: spyC,
deep: true
},
qux: {
handler: 'onQuxChange'
}
},
methods: {
onFooChange: spyA
onFooChange: spyA,
onQuxChange: spyD
},
render() {
ctx = this
Expand Down Expand Up @@ -164,6 +170,11 @@ describe('api: options', () => {
expect(spyC).toHaveBeenCalledTimes(1)
// new and old objects have same identity
assertCall(spyC, 0, [{ qux: 4 }, { qux: 4 }])

ctx.qux++
await nextTick()
expect(spyD).toHaveBeenCalledTimes(1)
assertCall(spyD, 0, [5, 4])
})

test('watch array', async () => {
Expand Down
7 changes: 5 additions & 2 deletions packages/runtime-core/src/componentOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ export type ExtractComputedReturns<T extends any> = {
type WatchOptionItem =
| string
| WatchCallback
| { handler: WatchCallback } & WatchOptions
| { handler: WatchCallback | string } & WatchOptions

type ComponentWatchOptionItem = WatchOptionItem | WatchOptionItem[]

Expand Down Expand Up @@ -704,7 +704,10 @@ function createWatcher(
if (isArray(raw)) {
raw.forEach(r => createWatcher(r, ctx, publicThis, key))
} else {
watch(getter, raw.handler.bind(publicThis), raw)
const handler = isString(raw.handler)
? (ctx[raw.handler] as WatchCallback)
: raw.handler
watch(getter, handler.bind(publicThis), raw)
}
} else if (__DEV__) {
warn(`Invalid watch option: "${key}"`)
Expand Down

0 comments on commit 4fe36d5

Please sign in to comment.