diff --git a/src/core/instance/state.js b/src/core/instance/state.js index d2d8fa14998..1ba0ff0ec11 100644 --- a/src/core/instance/state.js +++ b/src/core/instance/state.js @@ -247,8 +247,12 @@ function initWatch (vm: Component, watch: Object) { } } -function createWatcher (vm: Component, key: string, handler: any) { - let options +function createWatcher ( + vm: Component, + keyOrFn: string | Function, + handler: any, + options?: Object +) { if (isPlainObject(handler)) { options = handler handler = handler.handler @@ -256,7 +260,7 @@ function createWatcher (vm: Component, key: string, handler: any) { if (typeof handler === 'string') { handler = vm[handler] } - vm.$watch(key, handler, options) + return vm.$watch(keyOrFn, handler, options) } export function stateMixin (Vue: Class) { @@ -287,10 +291,13 @@ export function stateMixin (Vue: Class) { Vue.prototype.$watch = function ( expOrFn: string | Function, - cb: Function, + cb: any, options?: Object ): Function { const vm: Component = this + if (isPlainObject(cb)) { + return createWatcher(vm, expOrFn, cb, options) + } options = options || {} options.user = true const watcher = new Watcher(vm, expOrFn, cb, options) diff --git a/test/unit/features/instance/methods-data.spec.js b/test/unit/features/instance/methods-data.spec.js index eb63bf4274d..49e9b6f5009 100644 --- a/test/unit/features/instance/methods-data.spec.js +++ b/test/unit/features/instance/methods-data.spec.js @@ -21,14 +21,17 @@ describe('Instance methods data', () => { describe('$watch', () => { let vm, spy beforeEach(() => { + spy = jasmine.createSpy('watch') vm = new Vue({ data: { a: { b: 1 } + }, + methods: { + foo: spy } }) - spy = jasmine.createSpy('watch') }) it('basic usage', done => { @@ -81,6 +84,30 @@ describe('Instance methods data', () => { }).then(done) }) + it('handler option', done => { + var oldA = vm.a + vm.$watch('a', { + handler: spy, + deep: true + }) + vm.a.b = 2 + waitForUpdate(() => { + expect(spy).toHaveBeenCalledWith(oldA, oldA) + vm.a = { b: 3 } + }).then(() => { + expect(spy).toHaveBeenCalledWith(vm.a, oldA) + }).then(done) + }) + + it('handler option in string', () => { + vm.$watch('a.b', { + handler: 'foo', + immediate: true + }) + expect(spy.calls.count()).toBe(1) + expect(spy).toHaveBeenCalledWith(1) + }) + it('warn expresssion', () => { vm.$watch('a + b', spy) expect('Watcher only accepts simple dot-delimited paths').toHaveBeenWarned()