Bladeren bron

support object style dispatch (#315)

katashin 8 jaren geleden
bovenliggende
commit
96084f5b83
2 gewijzigde bestanden met toevoegingen van 46 en 0 verwijderingen
  1. 5 0
      src/index.js
  2. 41 0
      test/unit/test.js

+ 5 - 0
src/index.js

@@ -85,6 +85,11 @@ class Store {
   }
 
   dispatch (type, payload) {
+    // check object-style dispatch
+    if (isObject(type) && type.type) {
+      payload = type
+      type = type.type
+    }
     const entry = this._actions[type]
     if (!entry) {
       console.error(`[vuex] unknown action type: ${type}`)

+ 41 - 0
test/unit/test.js

@@ -23,6 +23,24 @@ describe('Vuex', () => {
     expect(store.state.a).toBe(3)
   })
 
+  it('committing with object style', () => {
+    const store = new Vuex.Store({
+      state: {
+        a: 1
+      },
+      mutations: {
+        [TEST] (state, payload) {
+          state.a += payload.amount
+        }
+      }
+    })
+    store.commit({
+      type: TEST,
+      amount: 2
+    })
+    expect(store.state.a).toBe(3)
+  })
+
   it('dispatching actions, sync', () => {
     const store = new Vuex.Store({
       state: {
@@ -43,6 +61,29 @@ describe('Vuex', () => {
     expect(store.state.a).toBe(3)
   })
 
+  it('dispatching with object style', () => {
+    const store = new Vuex.Store({
+      state: {
+        a: 1
+      },
+      mutations: {
+        [TEST] (state, n) {
+          state.a += n
+        }
+      },
+      actions: {
+        [TEST] ({ commit }, payload) {
+          commit(TEST, payload.amount)
+        }
+      }
+    })
+    store.dispatch({
+      type: TEST,
+      amount: 2
+    })
+    expect(store.state.a).toBe(3)
+  })
+
   it('dispatching actions, with returned Promise', done => {
     const store = new Vuex.Store({
       state: {