Jelajahi Sumber

add watch api

Evan You 9 tahun lalu
induk
melakukan
8aa242abbf
2 mengubah file dengan 42 tambahan dan 0 penghapusan
  1. 18 0
      src/index.js
  2. 24 0
      test/test.js

+ 18 - 0
src/index.js

@@ -98,6 +98,24 @@ export class Store {
     }
   }
 
+  /**
+   * Watch state changes on the store.
+   * Same API as Vue's $watch, except when watching a function,
+   * the function gets the state as the first argument.
+   *
+   * @param {String|Function} expOrFn
+   * @param {Function} cb
+   * @param {Object} [options]
+   */
+
+  watch (expOrFn, cb, options) {
+    return this._vm.$watch(() => {
+      return typeof expOrFn === 'function'
+        ? expOrFn(this.state)
+        : this._vm.$get(expOrFn)
+    }, cb, options)
+  }
+
   /**
    * Hot update actions and mutations.
    *

+ 24 - 0
test/test.js

@@ -246,6 +246,30 @@ describe('Vuex', () => {
     expect(mutations[0].nextState.a).to.equal(3)
   })
 
+  it('watch', function (done) {
+    const store = new Vuex.Store({
+      state: {
+        a: 1
+      },
+      mutations: {
+        [TEST]: state => state.a++
+      }
+    })
+    let watchedValueOne, watchedValueTwo
+    store.watch(({ a }) => a, val => {
+      watchedValueOne = val
+    })
+    store.watch('a', val => {
+      watchedValueTwo = val
+    })
+    store.dispatch(TEST)
+    Vue.nextTick(() => {
+      expect(watchedValueOne).to.equal(2)
+      expect(watchedValueTwo).to.equal(2)
+      done()
+    })
+  })
+
   it('strict mode: warn mutations outside of handlers', function () {
     const store = new Vuex.Store({
       state: {