Skip to content

Commit 8aa242a

Browse files
committed
add watch api
1 parent 77f2b35 commit 8aa242a

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/index.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,24 @@ export class Store {
9898
}
9999
}
100100

101+
/**
102+
* Watch state changes on the store.
103+
* Same API as Vue's $watch, except when watching a function,
104+
* the function gets the state as the first argument.
105+
*
106+
* @param {String|Function} expOrFn
107+
* @param {Function} cb
108+
* @param {Object} [options]
109+
*/
110+
111+
watch (expOrFn, cb, options) {
112+
return this._vm.$watch(() => {
113+
return typeof expOrFn === 'function'
114+
? expOrFn(this.state)
115+
: this._vm.$get(expOrFn)
116+
}, cb, options)
117+
}
118+
101119
/**
102120
* Hot update actions and mutations.
103121
*

test/test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,30 @@ describe('Vuex', () => {
246246
expect(mutations[0].nextState.a).to.equal(3)
247247
})
248248

249+
it('watch', function (done) {
250+
const store = new Vuex.Store({
251+
state: {
252+
a: 1
253+
},
254+
mutations: {
255+
[TEST]: state => state.a++
256+
}
257+
})
258+
let watchedValueOne, watchedValueTwo
259+
store.watch(({ a }) => a, val => {
260+
watchedValueOne = val
261+
})
262+
store.watch('a', val => {
263+
watchedValueTwo = val
264+
})
265+
store.dispatch(TEST)
266+
Vue.nextTick(() => {
267+
expect(watchedValueOne).to.equal(2)
268+
expect(watchedValueTwo).to.equal(2)
269+
done()
270+
})
271+
})
272+
249273
it('strict mode: warn mutations outside of handlers', function () {
250274
const store = new Vuex.Store({
251275
state: {

0 commit comments

Comments
 (0)