Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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