Przeglądaj źródła

middleware before/after

Evan You 9 lat temu
rodzic
commit
f9ded9b03f
2 zmienionych plików z 12 dodań i 6 usunięć
  1. 3 3
      examples/todomvc/vuex/middlewares.js
  2. 9 3
      src/index.js

+ 3 - 3
examples/todomvc/vuex/middlewares.js

@@ -1,7 +1,7 @@
 import { STORAGE_KEY } from './index'
 
-export default [
-  function (action, state) {
+export default [{
+  after: function (action, state) {
     localStorage.setItem(STORAGE_KEY, JSON.stringify(state.todos))
   }
-]
+}]

+ 9 - 3
src/index.js

@@ -67,14 +67,20 @@ export default class Vuex {
 
   dispatch (type, ...payload) {
     const mutation = this._mutations[type]
+    const state = this.state
     if (mutation) {
+      // middleware before hooks
+      this._middlewares.forEach(middleware => {
+        middleware.before && middleware.before({ type, payload }, state)
+      })
       if (Array.isArray(mutation)) {
-        mutation.forEach(m => m(this.state, ...payload))
+        mutation.forEach(m => m(state, ...payload))
       } else {
-        mutation(this.state, ...payload)
+        mutation(state, ...payload)
       }
+      // middleware after hooks
       this._middlewares.forEach(middleware => {
-        middleware({ type, payload }, this.state)
+        middleware.after && middleware.after({ type, payload }, state)
       })
     } else {
       console.warn(`[vuex] Unknown mutation: ${ type }`)