File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -98,6 +98,24 @@ export class Store {
98
98
}
99
99
}
100
100
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
+
101
119
/**
102
120
* Hot update actions and mutations.
103
121
*
Original file line number Diff line number Diff line change @@ -246,6 +246,30 @@ describe('Vuex', () => {
246
246
expect ( mutations [ 0 ] . nextState . a ) . to . equal ( 3 )
247
247
} )
248
248
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
+
249
273
it ( 'strict mode: warn mutations outside of handlers' , function ( ) {
250
274
const store = new Vuex . Store ( {
251
275
state : {
You can’t perform that action at this time.
0 commit comments