From ec8fd10cec61c33c7c8056413a1c609ac90e1215 Mon Sep 17 00:00:00 2001 From: edison Date: Tue, 9 Feb 2021 15:00:32 +0800 Subject: [PATCH] fix(runtime-core): instanceWatch should pass `this.proxy` to source as the first argument (#2753) --- .../runtime-core/__tests__/apiWatch.spec.ts | 22 ++++++++++++++++++- packages/runtime-core/src/apiWatch.ts | 8 +++++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/packages/runtime-core/__tests__/apiWatch.spec.ts b/packages/runtime-core/__tests__/apiWatch.spec.ts index 1836b6e9..30248072 100644 --- a/packages/runtime-core/__tests__/apiWatch.spec.ts +++ b/packages/runtime-core/__tests__/apiWatch.spec.ts @@ -15,7 +15,8 @@ import { nodeOps, serializeInner, TestElement, - h + h, + createApp } from '@vue/runtime-test' import { ITERATE_KEY, @@ -857,4 +858,23 @@ describe('api: watch', () => { expect(instance!.effects![0].active).toBe(false) }) + + test('this.$watch should pass `this.proxy` to watch source as the first argument ', () => { + let instance: any + const source = jest.fn() + + const Comp = defineComponent({ + render() {}, + created(this: any) { + instance = this + this.$watch(source, function() {}) + } + }) + + const root = nodeOps.createElement('div') + createApp(Comp).mount(root) + + expect(instance).toBeDefined() + expect(source).toHaveBeenCalledWith(instance) + }) }) diff --git a/packages/runtime-core/src/apiWatch.ts b/packages/runtime-core/src/apiWatch.ts index 55bbbb8f..0e0a549c 100644 --- a/packages/runtime-core/src/apiWatch.ts +++ b/packages/runtime-core/src/apiWatch.ts @@ -181,7 +181,9 @@ function doWatch( } else if (isReactive(s)) { return traverse(s) } else if (isFunction(s)) { - return callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER) + return callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER, [ + instance && (instance.proxy as any) + ]) } else { __DEV__ && warnInvalidSource(s) } @@ -190,7 +192,9 @@ function doWatch( if (cb) { // getter with cb getter = () => - callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER) + callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER, [ + instance && (instance.proxy as any) + ]) } else { // no cb -> simple effect getter = () => {