Ver código fonte

Add store getters as second argument to store.watch() computed fn (solve #460) (#515)

* Batman!

* the first parameter of store.watch(), which is a function, now receives the store.getters object as its second argument.
* added unit test

Fullfills request #460

* remove unused constant

* reverse changes to /dist
Thorsten Lünborg 8 anos atrás
pai
commit
1b8136357f
2 arquivos alterados com 33 adições e 2 exclusões
  1. 1 1
      src/index.js
  2. 32 1
      test/unit/test.js

+ 1 - 1
src/index.js

@@ -124,7 +124,7 @@ class Store {
 
 
   watch (getter, cb, options) {
   watch (getter, cb, options) {
     assert(typeof getter === 'function', `store.watch only accepts a function.`)
     assert(typeof getter === 'function', `store.watch only accepts a function.`)
-    return this._watcherVM.$watch(() => getter(this.state), cb, options)
+    return this._watcherVM.$watch(() => getter(this.state, this.getters), cb, options)
   }
   }
 
 
   replaceState (state) {
   replaceState (state) {

+ 32 - 1
test/unit/test.js

@@ -5,7 +5,6 @@ import Vuex, { mapState, mapMutations, mapGetters, mapActions } from '../../dist
 Vue.use(Vuex)
 Vue.use(Vuex)
 
 
 const TEST = 'TEST'
 const TEST = 'TEST'
-const TEST2 = 'TEST2'
 
 
 describe('Vuex', () => {
 describe('Vuex', () => {
   it('committing mutations', () => {
   it('committing mutations', () => {
@@ -1282,4 +1281,36 @@ describe('Vuex', () => {
       })
       })
     })
     })
   })
   })
+
+  it('watch: getter function has access to store\'s getters object', done => {
+    const store = new Vuex.Store({
+      state: {
+        count: 0
+      },
+      mutations: {
+        [TEST]: state => state.count++
+      },
+      getters: {
+        getCount: state => state.count
+      }
+    })
+
+    const getter = function getter (state, getters) {
+      return state.count
+    }
+    const spy = spyOn({ getter }, 'getter').and.callThrough()
+    const spyCb = jasmine.createSpy()
+
+    store.watch(spy, spyCb)
+
+    Vue.nextTick(() => {
+      store.commit(TEST)
+      expect(store.state.count).toBe(1)
+
+      Vue.nextTick(() => {
+        expect(spy).toHaveBeenCalledWith(store.state, store.getters)
+        done()
+      })
+    })
+  })
 })
 })