Skip to content

Commit

Permalink
make vm.$watch api consistent with watch option (vuejs#5645)
Browse files Browse the repository at this point in the history
  • Loading branch information
javoski authored and yyx990803 committed May 11, 2017
1 parent 8d56a49 commit e3ffa10
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
15 changes: 11 additions & 4 deletions src/core/instance/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,16 +247,20 @@ 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
}
if (typeof handler === 'string') {
handler = vm[handler]
}
vm.$watch(key, handler, options)
return vm.$watch(keyOrFn, handler, options)
}

export function stateMixin (Vue: Class<Component>) {
Expand Down Expand Up @@ -287,10 +291,13 @@ export function stateMixin (Vue: Class<Component>) {

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)
Expand Down
29 changes: 28 additions & 1 deletion test/unit/features/instance/methods-data.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit e3ffa10

Please sign in to comment.