make vm.$watch api consistent with watch option (#5645)

This commit is contained in:
AchillesJ 2017-05-11 15:10:40 +08:00 committed by Evan You
parent 8d56a498f3
commit e3ffa109b3
2 changed files with 39 additions and 5 deletions

View File

@ -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<Component>) {
@ -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)

View File

@ -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()