1. vuex #

Vuex是 Vue.js 的状态管理库,用于在应用中管理共享的、全局的状态。Vuex 的核心概念有 state、getter、mutation 和 action。

2. 安装 #

3.创建Store #

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
      <p>{{ count }}</p>
      <p>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
      </p>
    </div>
    <script src="vue.js"></script>
    <script src="vuex.js"></script>
    <script>
      const store = new Vuex.Store({
        state: {
          count: 0,
        },
        mutations: {
          increment: (state) => state.count++,
          decrement: (state) => state.count--,
        },
      });
      new Vue({
        el: "#app",
        computed: {
          count() {
            return store.state.count;
          },
        },
        methods: {
          increment() {
            store.commit("increment");
          },
          decrement() {
            store.commit("decrement");
          },
        },
      });
    </script>
  </body>
</html>

Vuex

var Vuex = {
    Store: function ({ state, mutations }) {
        this.state = Vue.observable(state);
        this.commit = (type) => {
            mutations[type](state);
        };
    }
};

4.state #

在 Vuex 中,state 是存储全局共享状态的地方。每一个 Vuex store 都有自己的 state,state 是一个对象,其中包含了全局的状态数据。通过这个单一状态树,我们可以获取全局的状态,进行状态的更改,并对状态的更改进行响应。

4.1 state #

这是一个简单的 Vuex store 的例子: 在这个例子中,我们定义了一个状态 count,初始值为 0。 要访问状态对象,你可以使用 store.state

  <body>
    <div id="app"></div>
    <script src="vue.js"></script>
    <script src="vuex.js"></script>
    <script>
      const store = new Vuex.Store({
        state: {
          count: 0,
        },
      });
      console.log(store.state.count);
    </script>
  </body>

4.2 在 Vue 组件中获得 Vuex 状态 #

那么我们如何在 Vue 组件中展示状态呢?由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:

  <body>
    <div id="app">{{count}}</div>
    <script src="vue.js"></script>
    <script src="vuex.js"></script>
    <script>
      const store = new Vuex.Store({
        state: {
          count: 0,
        },
      });
      var vm = new Vue({
        el: "#app",
        computed: {
          count() {
            return store.state.count;
          },
        },
      });
    </script>
  </body>

每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。

4.3 store选项 #

然而,这种模式导致组件依赖全局状态单例。在模块化的构建系统中,在每个需要使用 state 的组件中需要频繁地导入,并且在测试组件时需要模拟状态。

Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):

通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <p>{{doubleCount}}</p>
        <button @click="increase">+</button>
        <button @click="decrease">-</button>
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
        Vue.use(Vuex);
        const store = new Vuex.Store({
            state:{
                count:0
            },
            mutations:{
                add(state){
                    state.count++;
                },
                minus(state){
                    state.count--;
                }
            }
        })
        var vm = new Vue({
            el:'#app',
            store,
            computed:{
                doubleCount(){
                    return this.$store.state.count*2;
                }
            },
            methods:{
                increase(){
                    store.commit('add');
                },
                decrease(){
                    store.commit('minus');
                }
            }
        });
    </script>
</body>
</html>

Vuex

var Vuex = {
  Store: function ({state,mutations}) {
    this.state = Vue.observable(state);
    this.commit = function (type) {
      mutations[type]?.(this.state);
    };
  },
  install(Vue) {
    Vue.mixin({
        beforeCreate() {
            if (this.$options && this.$options.store) {
                this.$store = this.$options.store;
            }
        },
    });
},
};

4.4 mapState #

当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <p>{{count}}</p>
        <p>{{doubleCount}}</p>
        <button @click="increase">+</button>
        <button @click="decrease">-</button>
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
        Vue.use(Vuex);
        const store = new Vuex.Store({
            state:{
                count:0
            },
            mutations:{
                add(state){
                    state.count++;
                },
                minus(state){
                    state.count--;
                }
            }
        })
        var vm = new Vue({
            el:'#app',
            store,
            computed:{
                doubleCount(){
                    return this.$store.state.count*2;
                },
                ...Vuex.mapState({
                    count:state=>state.count
                })
            },
            methods:{
                increase(){
                    store.commit('add');
                },
                decrease(){
                    store.commit('minus');
                }
            }
        });
    </script>
</body>
</html>
var Vuex = {
  Store: function ({ state, mutations }) {
    this.state = Vue.observable(state);
    this.commit = function (type) {
      mutations[type]?.(this.state);
    };
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        if (this.$options && this.$options.store) {
          this.$store = this.$options.store;
        }
      },
    });
  },
+ mapState(map) {
+   const computed = {};
+   for (const [key, value] of Object.entries(map)) {
+     if (typeof value === 'function') {
+       computed[key] = function() {
+         return value.call(this, this.$store.state);
+       };
+     } else if (typeof value === 'string') {
+       computed[key] = function() {
+         return this.$store.state[value];
+       };
+     }
+   }
+   return computed;
+ }
};

5.getters #

有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数 如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它——无论哪种方式都不是很理想。

5.1 定义getter #

Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

Getter 接受 state 作为其第一个参数:

通过属性访问

Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">

    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
        Vue.use(Vuex);
        const store = new Vuex.Store({
            state:{
                todos: [
                    { id: 1, text: "eat", done: true },
                    { id: 2, text: "sleep", done: true },
                    { id: 3, text: "play", done: false },
                ],
            },
            getters: {
                doneTodos: (state) => {
                    return state.todos.filter((todo) => todo.done);
                }
            }
        })
        console.log(store.getters.doneTodos);
    </script>
</body>
</html>
var Vuex = {
+ Store: function ({ state, mutations,getters  }) {
    this.state = Vue.observable(state);
+   this.getters = {};
    this.commit = function (type) {
      mutations[type]?.(this.state);
    };
+   if (getters) {
+     for (const [key, value] of Object.entries(getters)) {
+       Object.defineProperty(this.getters, key, {
+         get: () => {
+           return value(this.state);
+         },
+         enumerable: true
+       });
+     }
+   }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        if (this.$options && this.$options.store) {
          this.$store = this.$options.store;
        }
      },
    });
  },
  mapState(map) {
    const computed = {};
    for (const [key, value] of Object.entries(map)) {
      if (typeof value === 'function') {
        computed[key] = function() {
          return value.call(this, this.$store.state);
        };
      } else if (typeof value === 'string') {
        computed[key] = function() {
          return this.$store.state[value];
        };
      }
    }
    return computed;
  }
};

Getter 也可以接受其他 getter 作为第二个参数:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">

    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
        Vue.use(Vuex);
        const store = new Vuex.Store({
            state:{
                todos: [
                    { id: 1, text: "eat", done: true },
                    { id: 2, text: "sleep", done: true },
                    { id: 3, text: "play", done: false },
                ],
            },
            getters: {
                doneTodos: (state) => {
                    return state.todos.filter((todo) => todo.done);
                },
+               doneTodosCount: (state, getters) => {
+                   return getters.doneTodos.length;
+               }
            }
        })
        console.log(store.getters.doneTodos);
        console.log(store.getters.doneTodosCount);
    </script>
</body>
</html>
var Vuex = {
  Store: function ({ state, mutations,getters  }) {
    this.state = Vue.observable(state);
    this.getters = {};
    this.commit = function (type) {
      mutations[type]?.(this.state);
    };
+   if (getters) {
+     const computedGetters = {};
+     for (const [key, value] of Object.entries(getters)) {
+       computedGetters[key] = () => {
+         return value(this.state, this.getters);
+       };
+     }
+     for (const [key, value] of Object.entries(computedGetters)) {
+       Object.defineProperty(this.getters, key, {
+         get: value,
+         enumerable: true
+       });
+     }
+   }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        if (this.$options && this.$options.store) {
          this.$store = this.$options.store;
        }
      },
    });
  },
  mapState(map) {
    const computed = {};
    for (const [key, value] of Object.entries(map)) {
      if (typeof value === 'function') {
        computed[key] = function() {
          return value.call(this, this.$store.state);
        };
      } else if (typeof value === 'string') {
        computed[key] = function() {
          return this.$store.state[value];
        };
      }
    }
    return computed;
  }
};

5.2 组件中使用 #

我们可以很容易地在任何组件中使用它:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        doneTodosCount: {{doneTodosCount}}
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
        Vue.use(Vuex);
        const store = new Vuex.Store({
            state:{
                todos: [
                    { id: 1, text: "eat", done: true },
                    { id: 2, text: "sleep", done: true },
                    { id: 3, text: "play", done: false },
                ],
            },
            getters: {
                doneTodos: (state) => {
                    return state.todos.filter((todo) => todo.done);
                },
                doneTodosCount: (state, getters) => {
                    return getters.doneTodos.length;
                }
            }
        })
+       var vm = new Vue({
+           el: '#app',
+           store,
+           computed: {
+               doneTodosCount() {
+                   return this.$store.getters.doneTodosCount
+               }
+           }
+       })
    </script>
</body>
</html>

注意,getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的

5.3 通过方法访问 #

你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        doneTodosCount: {{doneTodosCount}}
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
        Vue.use(Vuex);
        const store = new Vuex.Store({
            state:{
                todos: [
                    { id: 1, text: "eat", done: true },
                    { id: 2, text: "sleep", done: true },
                    { id: 3, text: "play", done: false },
                ],
            },
            getters: {
                doneTodos: (state) => {
                    return state.todos.filter((todo) => todo.done);
                },
                doneTodosCount: (state, getters) => {
                    return getters.doneTodos.length;
                },
+               getTodoById: (state) => (id) => {
+                  return state.todos.find(todo => todo.id === id)
+               }
            }
        })
        var vm = new Vue({
            el: '#app',
            store,
            computed: {
                doneTodosCount() {
                    return this.$store.getters.doneTodosCount
                }
            }
        })
+       console.log(store.getters.getTodoById(2));
    </script>
</body>
</html>

注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。

5.4 mapGetters 辅助函数 #

mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性: 如果你想将一个 getter 属性另取一个名字,使用对象形式:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        doneTodosCount: {{doneTodosCount}}
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
        Vue.use(Vuex);
        const store = new Vuex.Store({
            state:{
                todos: [
                    { id: 1, text: "eat", done: true },
                    { id: 2, text: "sleep", done: true },
                    { id: 3, text: "play", done: false },
                ],
            },
            getters: {
                doneTodos: (state) => {
                    return state.todos.filter((todo) => todo.done);
                },
                doneTodosCount: (state, getters) => {
                    return getters.doneTodos.length;
                },
                getTodoById: (state) => (id) => {
                   return state.todos.find(todo => todo.id === id)
               }
            }
        })
        var vm = new Vue({
            el: '#app',
            store,
            computed: {
                doneTodosCount() {
                    return this.$store.getters.doneTodosCount
                },
+               ...Vuex.mapGetters(['doneTodos'])
            }
        })
+       console.log(vm.doneTodos);
    </script>
</body>
</html>
var Vuex = {
  Store: function ({ state, mutations,getters  }) {
    this.state = Vue.observable(state);
    this.getters = {};
    this.commit = function (type) {
      mutations[type]?.(this.state);
    };
    if (getters) {
      const computedGetters = {};
      for (const [key, value] of Object.entries(getters)) {
        computedGetters[key] = () => {
          return value(this.state, this.getters);
        };
      }
      for (const [key, value] of Object.entries(computedGetters)) {
        Object.defineProperty(this.getters, key, {
          get: value,
          enumerable: true
        });
      }
    }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        if (this.$options && this.$options.store) {
          this.$store = this.$options.store;
        }
      },
    });
  },
  mapState(map) {
    const computed = {};
    for (const [key, value] of Object.entries(map)) {
      if (typeof value === 'function') {
        computed[key] = function() {
          return value.call(this, this.$store.state);
        };
      } else if (typeof value === 'string') {
        computed[key] = function() {
          return this.$store.state[value];
        };
      }
    }
    return computed;
  },
+ mapGetters(getterNames) {
+   const computed = {};
+   for (const name of getterNames) {
+     computed[name] = function() {
+       return this.$store.getters[name];
+     };
+   }
+   return computed;
+ }
};

6.Mutation #

6.1 定义mutation #

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。 Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。 这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数: 你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">

    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
      const store = new Vuex.Store({
        state: {
          count: 0,
        },
        mutations: {
          add(state) {
            state.count++;
          },
        },
      });
      console.log(store.state.count);
      store.commit("add");
      console.log(store.state.count);
    </script>
</body>
</html>

6.2 提交载荷(Payload) #

你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload): 在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
      const store = new Vuex.Store({
        state: {
          count: 0,
        },
        mutations: {
+         add(state,payload) {
+           state.count+=payload.amount;
+         }
        },
      });
      console.log(store.state.count);
+     store.commit("add",{amount:5});
      console.log(store.state.count);
    </script>
</body>
</html>
var Vuex = {
  Store: function ({ state, mutations,getters  }) {
    this.state = Vue.observable(state);
    this.getters = {};
+   this.commit = function (type, payload) {
+     mutations[type]?.(this.state, payload);
+   };
    if (getters) {
      const computedGetters = {};
      for (const [key, value] of Object.entries(getters)) {
        computedGetters[key] = () => {
          return value(this.state, this.getters);
        };
      }
      for (const [key, value] of Object.entries(computedGetters)) {
        Object.defineProperty(this.getters, key, {
          get: value,
          enumerable: true
        });
      }
    }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        if (this.$options && this.$options.store) {
          this.$store = this.$options.store;
        }
      },
    });
  },
  mapState(map) {
    const computed = {};
    for (const [key, value] of Object.entries(map)) {
      if (typeof value === 'function') {
        computed[key] = function() {
          return value.call(this, this.$store.state);
        };
      } else if (typeof value === 'string') {
        computed[key] = function() {
          return this.$store.state[value];
        };
      }
    }
    return computed;
  },
  mapGetters(getterNames) {
    const computed = {};
    for (const name of getterNames) {
      computed[name] = function() {
        return this.$store.getters[name];
      };
    }
    return computed;
  }
};

6.3 Mutation必须是同步函数 #

一条重要的原则就是要记住 mutation 必须是同步函数。为什么?请参考下面的例子:

mutations: {
  someMutation (state) {
    api.callAsyncMethod(() => {
      state.count++
    })
  }
}

现在想象,我们正在 debug 一个 app 并且观察 devtool 中的 mutation 日志。每一条 mutation 被记录,devtools 都需要捕捉到前一状态和后一状态的快照。然而,在上面的例子中 mutation 中的异步函数中的回调让这不可能完成:因为当 mutation 触发的时候,回调函数还没有被调用,devtools 不知道什么时候回调函数实际上被调用——实质上任何在回调函数中进行的状态的改变都是不可追踪的。

6.4 在组件中提交Mutation #

你可以在组件中使用 this.$store.commit('xxx') 提交 mutation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
+       <p>{{count}}</p>
+       <button @click="add">+</button>
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
      Vue.use(Vuex);
      const store = new Vuex.Store({
        state: {
          count: 0,
        },
        mutations: {
          add(state,payload) {
            state.count+=payload.amount;
          }
        },
      });
      var vm = new Vue({
        el:'#app',
        store,
        computed:{
          count(){
            return this.$store.state.count;
          }
        },
        methods:{
+         add(){
+           this.$store.commit('add',{amount:5})
+         }
        }
      });
    </script>
</body>
</html>

6.5 辅助函数 #

或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <p>{{count}}</p>
        <button @click="add">+</button>
+       <button @click="minus">-</button>
    </div>
    <script src="vue.js"></script>
    <script src="my-vuex.js"></script>
    <script>
      Vue.use(Vuex);
      const store = new Vuex.Store({
        state: {
          count: 0,
        },
        mutations: {
          add(state,payload) {
            state.count+=payload.amount;
          },
+         minus(state) {
+           state.count-=1;
+         }
        },
      });
      var vm = new Vue({
        el:'#app',
        store,
        computed:{
          count(){
            return this.$store.state.count;
          }
        },
        methods:{
          add(){
            this.$store.commit('add',{amount:5})
          },
+         ...Vuex.mapMutations(["minus"]),
        }
      });
    </script>
</body>
</html>
var Vuex = {
  Store: function ({ state, mutations,getters  }) {
    this.state = Vue.observable(state);
    this.getters = {};
    this.commit = function (type, payload) {
      mutations[type]?.(this.state, payload);
    };
    if (getters) {
      const computedGetters = {};
      for (const [key, value] of Object.entries(getters)) {
        computedGetters[key] = () => {
          return value(this.state, this.getters);
        };
      }
      for (const [key, value] of Object.entries(computedGetters)) {
        Object.defineProperty(this.getters, key, {
          get: value,
          enumerable: true
        });
      }
    }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        if (this.$options && this.$options.store) {
          this.$store = this.$options.store;
        }
      },
    });
  },
  mapState(map) {
    const computed = {};
    for (const [key, value] of Object.entries(map)) {
      if (typeof value === 'function') {
        computed[key] = function() {
          return value.call(this, this.$store.state);
        };
      } else if (typeof value === 'string') {
        computed[key] = function() {
          return this.$store.state[value];
        };
      }
    }
    return computed;
  },
  mapGetters(getterNames) {
    const computed = {};
    for (const name of getterNames) {
      computed[name] = function() {
        return this.$store.getters[name];
      };
    }
    return computed;
  },
+ mapMutations(mutationNames) {
+   const methods = {};
+   for (const name of mutationNames) {
+     methods[name] = function(payload) {
+       this.$store.commit(name, payload);
+     };
+   }
+   return methods;
+ }
};

7.Action #

7.1 Action定义 #

Action 类似于 mutation,不同在于:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
  </div>
  <script src="vue.js"></script>
  <script src="my-vuex.js"></script>
  <script>
    Vue.use(Vuex);
    const store = new Vuex.Store({
      state: {
        count: 0,
      },
      mutations: {
        add(state) {
          state.count++;
        },
      },
      actions: {
        increment(context) {
          context.commit("add");
        },
      },
    });
  </script>
</body>
</html>

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。

7.2 分发Action #

Action 通过 store.dispatch 方法触发:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
  </div>
  <script src="vue.js"></script>
  <script src="my-vuex.js"></script>
  <script>
    Vue.use(Vuex);
    const store = new Vuex.Store({
      state: {
        count: 0,
      },
      mutations: {
        add(state) {
          state.count++;
        },
      },
      actions: {
        increment(context) {
          context.commit("add");
        },
      },
    });
+   console.log(store.state.count)
+   store.dispatch('increment')
+   console.log(store.state.count)
  </script>
</body>
</html>
//const isFunction = val => typeof val === 'function';
const isString = val => typeof val === 'string';
//const isPlainObject = val => typeof val === 'object' && Object.getPrototypeOf(val) === Object.prototype;
var Vuex = {
  Store: function ({
    state,
    getters,
    mutations,
+   actions
  }) {
    this.state = Vue.observable(state);
+   this.actions = actions || {};
+   this.dispatch = function (type, payload) {
+     if (typeof this.actions[type] === 'function') {
+       return this.actions[type](this, payload);
+     }
+   };
    this.commit = (type, payload) => {
      if (isPlainObject(type)) {
        payload = type;
        type = type.type;
      }
      mutations[type]?.(this.state, payload);
    };
    this.getters = {};
    if (getters) {
      for (const [key, value] of Object.entries(getters)) {
        Object.defineProperty(this.getters, key, {
          get: () => {
            return value(this.state, this.getters);
          }
        });
      }
    }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        console.log(this);
        if (this.$options.store) {
          this.$store = this.$options.store;
        } else if (this.$parent) {
          this.$store = this.$parent.$store;
        }
      }
    });
  },
  mapState(map) {
    let computed = {};
    if (Array.isArray(map)) {
      map.forEach(key => {
        computed[key] = function () {
          return this.$store.state[key];
        };
      });
    } else {
      for (const [key, value] of Object.entries(map)) {
        if (isFunction(value)) {
          computed[key] = function () {
            return value.call(this, this.$store.state);
          };
        } else if (isString(value)) {
          computed[key] = function () {
            return this.$store.state[value];
          };
        }
      }
    }
    return computed;
  },
  mapGetters(getterNames) {
    let computed = {};
    getterNames.forEach(getterName => {
      computed[getterName] = function () {
        return this.$store.getters[getterName];
      };
    });
    return computed;
  },
  mapMutations(mutationNames) {
    const methods = {};
    mutationNames.forEach(mutationName => {
      methods[mutationName] = function (payload) {
        this.$store.commit(mutationName, payload);
      };
    });
    return methods;
  }
};

7.3 异步操作 #

乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
+   <p>{{count}}</p>
+   <button @click="increment">increment</button>
+   <button @click="incrementAsync">incrementAsync</button>
  </div>
  <script src="vue.js"></script>
  <script src="my-vuex.js"></script>
  <script>
    Vue.use(Vuex);
    const store = new Vuex.Store({
      state: {
        count: 0,
      },
      mutations: {
        add(state) {
          state.count++;
        },
      },
      actions: {
        increment(context) {
          context.commit("add");
        },
        incrementAsync(context) {
            setTimeout(() => {
              context.commit("add");
            }, 1000);
        },
      },
    });
+   var vm = new Vue({
+     el: "#app",
+     store,
+     computed: {
+       count() {
+         return this.$store.state.count;
+       },
+     },
+     methods: {
+       increment() {
+         this.$store.dispatch("increment");
+       },
+       incrementAsync() {
+         this.$store.dispatch("incrementAsync");
+       },
+     },
+   });
  </script>
</body>
</html>

7.4 辅助函数 #

或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>{{count}}</p>
    <button @click="increment">increment</button>
    <button @click="incrementAsync">incrementAsync</button>
  </div>
  <script src="vue.js"></script>
  <script src="my-vuex.js"></script>
  <script>
    Vue.use(Vuex);
    const store = new Vuex.Store({
      state: {
        count: 0,
      },
      mutations: {
        add(state) {
          state.count++;
        },
      },
      actions: {
        increment(context) {
          context.commit("add");
        },
        incrementAsync(context) {
            setTimeout(() => {
              context.commit("add");
            }, 1000);
        },
      },
    });
    var vm = new Vue({
      el: "#app",
      store,
      computed: {
        count() {
          return this.$store.state.count;
        },
      },
      methods: {
+       ...Vuex.mapActions(['increment','incrementAsync'])
      },
    });
  </script>
</body>
</html>
//const isFunction = val => typeof val === 'function';
const isString = val => typeof val === 'string';
//const isPlainObject = val => typeof val === 'object' && Object.getPrototypeOf(val) === Object.prototype;
var Vuex = {
  Store: function ({
    state,
    getters,
    mutations,
    actions
  }) {
    this.state = Vue.observable(state);
    this.actions = actions || {};
    this.dispatch = function (type, payload) {
      if (typeof this.actions[type] === 'function') {
        return this.actions[type](this, payload);
      }
    };
    this.commit = (type, payload) => {
      if (isPlainObject(type)) {
        payload = type;
        type = type.type;
      }
      mutations[type]?.(this.state, payload);
    };
    this.getters = {};
    if (getters) {
      for (const [key, value] of Object.entries(getters)) {
        Object.defineProperty(this.getters, key, {
          get: () => {
            return value(this.state, this.getters);
          }
        });
      }
    }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        console.log(this);
        if (this.$options.store) {
          this.$store = this.$options.store;
        } else if (this.$parent) {
          this.$store = this.$parent.$store;
        }
      }
    });
  },
  mapState(map) {
    let computed = {};
    if (Array.isArray(map)) {
      map.forEach(key => {
        computed[key] = function () {
          return this.$store.state[key];
        };
      });
    } else {
      for (const [key, value] of Object.entries(map)) {
        if (isFunction(value)) {
          computed[key] = function () {
            return value.call(this, this.$store.state);
          };
        } else if (isString(value)) {
          computed[key] = function () {
            return this.$store.state[value];
          };
        }
      }
    }
    return computed;
  },
  mapGetters(getterNames) {
    let computed = {};
    getterNames.forEach(getterName => {
      computed[getterName] = function () {
        return this.$store.getters[getterName];
      };
    });
    return computed;
  },
  mapMutations(mutationNames) {
    const methods = {};
    mutationNames.forEach(mutationName => {
      methods[mutationName] = function (payload) {
        this.$store.commit(mutationName, payload);
      };
    });
    return methods;
  },
+  mapActions(actionNames) {
+    const methods = {};
+    for (const name of actionNames) {
+      methods[name] = function (payload) {
+        this.$store.dispatch(name, payload);
+      };
+    }
+    return methods;
+  }
};

7.5 组合 Action #

Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?

首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>{{count}}</p>
    <button @click="increment">increment</button>
    <button @click="incrementAsync">incrementAsync</button>
    <button @click="change">change</button>
  </div>
  <script src="vue.js"></script>
  <script src="my-vuex.js"></script>
  <script>
    Vue.use(Vuex);
    const store = new Vuex.Store({
      state: {
        count: 0,
      },
      mutations: {
        add(state) {
          state.count++;
        },
      },
      actions: {
        increment(context) {
          context.commit("add");
        },
        incrementAsync(context) {
+         return new Promise((resolve) => {
+             setTimeout(() => {
+               context.commit("add");
+               resolve();
+             }, 1000);
+           });
        },
      },
    });
    var vm = new Vue({
      el: "#app",
      store,
      computed: {
        count() {
          return this.$store.state.count;
        },
      },
      methods: {
        ...Vuex.mapActions(['increment','incrementAsync']),
+       change() {
+           this.$store
+             .dispatch("incrementAsync")
+             .then(() => {
+               console.log("incrementAsync done");
+               return this.$store.dispatch("incrementAsync");
+             })
+             .then(() => {
+               console.log("incrementAsync done twice");
+             });
+         },
+     },
    });
  </script>
</body>
</html>

7.6 async/await #

最后,如果我们利用 async / await (opens new window),我们可以如下组合 action:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>{{count}}</p>
    <button @click="increment">increment</button>
    <button @click="incrementAsync">incrementAsync</button>
    <button @click="change">change</button>
  </div>
  <script src="vue.js"></script>
  <script src="my-vuex.js"></script>
  <script>
    Vue.use(Vuex);
    const store = new Vuex.Store({
      state: {
        count: 0,
      },
      mutations: {
        add(state) {
          state.count++;
        },
      },
      actions: {
        increment(context) {
          context.commit("add");
        },
        incrementAsync(context) {
          return new Promise((resolve) => {
              setTimeout(() => {
                context.commit("add");
                resolve();
              }, 1000);
            });
        },
      },
    });
    var vm = new Vue({
      el: "#app",
      store,
      computed: {
        count() {
          return this.$store.state.count;
        },
      },
      methods: {
        ...Vuex.mapActions(['increment','incrementAsync']),
+       async change() {
+         await this.$store.dispatch("incrementAsync");
+         console.log("incrementAsync done");
+         await this.$store.dispatch("incrementAsync");
+         console.log("incrementAsync done");
+       },
      },
    });
  </script>
</body>
</html>

一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

cart

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
      <div v-for="product in products">
          <p>{{ product.name }} - {{ product.price }}</p>
          <button @click="addToCart(product)">Add to Cart</button>
      </div>
      <h2>Your Cart</h2>
      <ul>
          <li v-for="item in cart.added">{{ item.name }} - {{ item.price }}</li>
      </ul>
      <button @click="checkout(cart.added)">Checkout</button>
  </div>
  <script src="vue.js"></script>
  <script src="vuex.js"></script>
  <script>
      Vue.use(Vuex);
      const types = {
          ADD_TO_CART: 'ADD_TO_CART',
          CHECKOUT_REQUEST: 'CHECKOUT_REQUEST',
          CHECKOUT_SUCCESS: 'CHECKOUT_SUCCESS',
          CHECKOUT_FAILURE: 'CHECKOUT_FAILURE'
      };
      const shop = {
          buyProducts(products, success, failure) {
              // Mocking an API call
              setTimeout(() => {
                  if (Math.random() > 0.5) {
                      success();
                  } else {
                      failure();
                  }
              }, 1000);
          }
      };
      const store = new Vuex.Store({
          state: {
              products: [
                  { id: 1, name: 'Apple', price: 1.00 },
                  { id: 2, name: 'Banana', price: 0.50 },
                  { id: 3, name: 'Cherry', price: 0.30 }
              ],
              cart: {
                  added: []
              }
          },
          mutations: {
              [types.ADD_TO_CART](state, product) {
                  state.cart.added.push(product);
              },
              [types.CHECKOUT_REQUEST](state) {
                  state.cart.added = [];
              },
              [types.CHECKOUT_SUCCESS](state) {
                  console.log("Checkout successful!");
              },
              [types.CHECKOUT_FAILURE](state, savedCartItems) {
                  state.cart.added = savedCartItems;
              }
          },
          actions: {
              addToCart({ commit }, product) {
                  commit(types.ADD_TO_CART, product);
              },
              checkout({ commit, state }, products) {
                  const savedCartItems = [...state.cart.added];
                  commit(types.CHECKOUT_REQUEST);
                  shop.buyProducts(
                      products,
                      () => commit(types.CHECKOUT_SUCCESS),
                      () => commit(types.CHECKOUT_FAILURE, savedCartItems)
                  );
              }
          }
      });
      new Vue({
          el: '#app',
          store,
          computed: {
              products() {
                  return this.$store.state.products;
              },
              cart() {
                  return this.$store.state.cart;
              }
          },
          methods: {
              addToCart(product) {
                  this.$store.dispatch('addToCart', product);
              },
              checkout(products) {
                  this.$store.dispatch('checkout', products);
              }
          }
      });
  </script>
</body>
</html>

8.Modules #

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

8.1 分割成模块 #

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象。 对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <p>rootCount:{{rootCount}}</p>
      <p>count1:{{count1}}</p>
      <p>doubleCount1:{{doubleCount1}}</p>
      <p>count2:{{count2}}</p>
      <p>doubleCount2:{{doubleCount2}}</p>
      <button @click="add">提交add的mutation</button>
      <button @click="increment">分发increment的action</button>
      <p>addRootCount:{{addRootCount}}</p>
      <button @click="incrementByRootCount">incrementByRootCount</button>
    </div>
    <script src="vue.js"></script>
    <script src="vuex2.js"></script>
    <script>
      Vue.use(Vuex);
      let counter1 = {
        state:{count:1},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          },
          incrementByRootCount({ state, commit, rootState }){
            commit('add',rootState.count);
          }
        },
        getters:{
          doubleCount1(state){
            return state.count*2;
          },
          addRootCount(state,getters,rootState){
            return state.count+rootState.count;
          }
        }
      }
      let counter2 = {
        state:{count:2},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          }
        },
        getters:{
          doubleCount2(state){
            return state.count*2;
          }
        }
      }
      const store = new Vuex.Store({
        state:{count:10},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          }
        },
        modules:{
          counter1,
          counter2
        }
      });
      var vm = new Vue({
        el:'#app',
        store,
        computed:{
          rootCount(){
            return this.$store.state.count;
          },
          count1(){
            return this.$store.state.counter1.count;
          },
          count2(){
            return this.$store.state.counter2.count;
          },
          doubleCount1(){
            return this.$store.getters.doubleCount1;
          },
          doubleCount2(){
            return this.$store.getters.doubleCount2;
          },
          addRootCount(){
            return this.$store.getters.addRootCount;
          }
        },
        methods:{
          add(){
            this.$store.commit('add');
          },
          increment(){
            this.$store.dispatch('increment');
          },
          incrementByRootCount(){
            this.$store.dispatch('incrementByRootCount');
          }
        }
      })
      console.log(store.state);//rootState
    </script>
  </body>
</html>

vuex.js

const isFunction = val => typeof val === 'function';
const isString = val => typeof val === 'string';
const isPlainObject = val => typeof val === 'object' && Object.getPrototypeOf(val) === Object.prototype;
var Vuex = {
+ Store: function ({state,getters,mutations,actions,modules}) {
    this.state = Vue.observable(state);
    this.actions = actions || {};
+   this.modules = modules || {};
+   this.mutations = mutations || {};
+   for (let moduleName in this.modules) {
+     this.state[moduleName] = Vue.observable(this.modules[moduleName].state);
+   }
    this.dispatch = function (type, payload) {
+     let result =  this.actions[type]?.(this, payload);
+     for (let moduleName in this.modules) {
+       this.modules[moduleName].actions[type]({...this,rootState:this.state}, payload)
+     }
+     return result;
    };
    this.commit = (type, payload) => {
      if (isPlainObject(type)) {
        payload = type;
        type = type.type;
      }
      mutations[type]?.(this.state, payload);
+     for (let moduleName in this.modules) {
+       this.modules[moduleName].mutations[type](this.state[moduleName], payload,this.state)
+     }
    };
    this.getters = {};
    if (getters) {
      for (const [key, value] of Object.entries(getters)) {
        Object.defineProperty(this.getters, key, {
          get: () => {
            return value(this.state, this.getters);
          }
        });
      }
    }
+   for (let moduleKey in this.modules) {
+     if (this.modules[moduleKey].getters) {
+       for (let key in this.modules[moduleKey].getters) {
+           Object.defineProperty(this.getters, key, {
+               get: () => {
+                   return this.modules[moduleKey].getters[key](this.state[moduleKey], this.getters, this.state);
+               }
+           });
+       }
+     }
+   }
+ },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        console.log(this);
        if (this.$options.store) {
          this.$store = this.$options.store;
        } else if (this.$parent) {
          this.$store = this.$parent.$store;
        }
      }
    });
  },
  mapState(map) {
    let computed = {};
    if (Array.isArray(map)) {
      map.forEach(key => {
        computed[key] = function () {
          return this.$store.state[key];
        };
      });
    } else {
      for (const [key, value] of Object.entries(map)) {
        if (isFunction(value)) {
          computed[key] = function () {
            return value.call(this, this.$store.state);
          };
        } else if (isString(value)) {
          computed[key] = function () {
            return this.$store.state[value];
          };
        }
      }
    }
    return computed;
  },
  mapGetters(getterNames) {
    let computed = {};
    getterNames.forEach(getterName => {
      computed[getterName] = function () {
        return this.$store.getters[getterName];
      };
    });
    return computed;
  },
  mapMutations(mutationNames) {
    const methods = {};
    mutationNames.forEach(mutationName => {
      methods[mutationName] = function (payload) {
        this.$store.commit(mutationName, payload);
      };
    });
    return methods;
  },
  mapActions(actionNames) {
    const methods = {};
    for (const name of actionNames) {
      methods[name] = function (payload) {
        this.$store.dispatch(name, payload);
      };
    }
    return methods;
  }
};

8.2 命名空间和访问全局 #

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。

如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。例如:

启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit。换言之,你在使用模块内容(module assets)时不需要在同一模块内额外添加空间名前缀。更改 namespaced 属性后不需要修改模块内的代码

在带命名空间的模块内访问全局内容(Global Assets) 如果你希望使用全局 state 和 getter,rootState 和 rootGetters 会作为第三和第四参数传入 getter,也会通过 context 对象的属性传入 action。

若需要在全局命名空间内分发 action 或提交 mutation,将 { root: true } 作为第三参数传给 dispatch 或 commit 即可。

在带命名空间的模块注册全局 action

若需要在带命名空间的模块注册全局 action,你可添加 root: true,并将这个 action 的定义放在函数 handler 中。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <p>rootCount:{{rootCount}}</p>
      <p>count1:{{count1}}</p>
      <p>doubleCount1:{{doubleCount1}}</p>
      <p>count2:{{count2}}</p>
      <p>doubleCount2:{{doubleCount2}}</p>
      <button @click="add">提交add的mutation</button>
      <button @click="increment">分发increment的action</button>
      <p>addRootCount:{{addRootCount}}</p>
      <button @click="incrementByRootCount">incrementByRootCount</button>
    </div>
    <script src="vue.js"></script>
    <script src="vuex2.js"></script>
    <script>
      Vue.use(Vuex);
      let counter1 = {
        namespaced: true,
        state:{count:1},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add',undefined,{root:true});
          },
          incrementByRootCount({ state, commit, rootState }){
            commit('add',rootState.count);
          }
        },
        getters:{
          doubleCount1(state){
            return state.count*2;
          },
          addRootCount(state,getters,rootState){
            return state.count+rootState.count;
          }
        }
      }
      let counter2 = {
        namespaced: true,
        state:{count:2},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          }
        },
        getters:{
          doubleCount2(state){
            return state.count*2;
          }
        }
      }
      const store = new Vuex.Store({
        state:{count:10},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          }
        },
        modules:{
          counter1,
          counter2
        }
      });
      var vm = new Vue({
        el:'#app',
        store,
        computed:{
          rootCount(){
            return this.$store.state.count;
          },
          count1(){
            return this.$store.state.counter1.count;
          },
          count2(){
            return this.$store.state.counter2.count;
          },
          doubleCount1(){
            return this.$store.getters[`counter1/doubleCount1`];
          },
          doubleCount2(){
            return this.$store.getters[`counter2/doubleCount2`];
          },
          addRootCount(){
            return this.$store.getters[`counter1/addRootCount`];
          }
        },
        methods:{
          add(){
            this.$store.commit('add');
          },
          increment(){
            this.$store.dispatch('counter1/increment');
          },
          incrementByRootCount(){
            this.$store.dispatch('counter1/incrementByRootCount');
          }
        }
      })
    </script>
  </body>
</html>
const isFunction = val => typeof val === 'function';
const isString = val => typeof val === 'string';
const isPlainObject = val => typeof val === 'object' && Object.getPrototypeOf(val) === Object.prototype;
var Vuex = {
  Store: function ({state,getters,mutations,actions,modules}) {
    this.state = Vue.observable(state);
    this.actions = actions || {};
    this.modules = modules || {};
    this.mutations = mutations || {};
    for (let moduleName in this.modules) {
      this.state[moduleName] = Vue.observable(this.modules[moduleName].state);
    }
+   this.dispatch = function (type, payload) {
+     let result =  this.actions[type]?.(this, payload);
+     for (let moduleName in this.modules) {
+       let module = this.modules[moduleName];
+       if(module.namespaced){
+         let parts = type.split('/');
+         if(parts[0]===moduleName){
+           const commit = (type,payload,options)=> this.commit(`${moduleName}/${type}`,payload,options);
+           module.actions[parts[1]]({...this,rootState:this.state,rootGetters:this.getters,commit}, payload)
+         }
+       }else{
+         module.actions[type]({...this,rootState:this.state}, payload)
+       }
+     }
+     return result;
+   };
+   this.commit = (type, payload,options) => {
      if (isPlainObject(type)) {
        payload = type;
        type = type.type;
      }
+     if(options && options.root){
+       type=type.split('/').pop();
+     }
      mutations[type]?.(this.state, payload);
      for (let moduleName in this.modules) {
+       let module = this.modules[moduleName];
+       if(module.namespaced){
+         let parts = type.split('/');
+         if(parts[0]===moduleName){
+           module.mutations[parts[1]](this.state[moduleName], payload,this.state)
+         }
+       }else{
+         module.mutations[type](this.state[moduleName], payload,this.state)
+       }
      }
    };
    this.getters = {};
    if (getters) {
      for (const [key, value] of Object.entries(getters)) {
        Object.defineProperty(this.getters, key, {
          get: () => {
            return value(this.state, this.getters);
          }
        });
      }
    }
+   for (let moduleName in this.modules) {
+     let module = this.modules[moduleName];
+     if (module.getters) {
+       for (let key in module.getters) {
+           const getterKey=`${moduleName}/${key}`;
+           Object.defineProperty(this.getters, getterKey, {
+               get: () => {
+                   return this.modules[moduleName].getters[key]?.(this.state[moduleName], module.getters, this.state, this.getters);
+               }
+           });
+       }
+     }
+   }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        console.log(this);
        if (this.$options.store) {
          this.$store = this.$options.store;
        } else if (this.$parent) {
          this.$store = this.$parent.$store;
        }
      }
    });
  },
  mapState(map) {
    let computed = {};
    if (Array.isArray(map)) {
      map.forEach(key => {
        computed[key] = function () {
          return this.$store.state[key];
        };
      });
    } else {
      for (const [key, value] of Object.entries(map)) {
        if (isFunction(value)) {
          computed[key] = function () {
            return value.call(this, this.$store.state);
          };
        } else if (isString(value)) {
          computed[key] = function () {
            return this.$store.state[value];
          };
        }
      }
    }
    return computed;
  },
  mapGetters(getterNames) {
    let computed = {};
    getterNames.forEach(getterName => {
      computed[getterName] = function () {
        return this.$store.getters[getterName];
      };
    });
    return computed;
  },
  mapMutations(mutationNames) {
    const methods = {};
    mutationNames.forEach(mutationName => {
      methods[mutationName] = function (payload) {
        this.$store.commit(mutationName, payload);
      };
    });
    return methods;
  },
  mapActions(actionNames) {
    const methods = {};
    for (const name of actionNames) {
      methods[name] = function (payload) {
        this.$store.dispatch(name, payload);
      };
    }
    return methods;
  }
};

8.3 带命名空间的绑定函数 #

当使用 mapState, mapGetters, mapActionsmapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐:

对于这种情况,你可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是上面的例子可以简化为:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <p>rootCount:{{rootCount}}</p>
      <p>count1:{{count1}}</p>
      <p>doubleCount1:{{doubleCount1}}</p>
      <p>count2:{{count2}}</p>
      <p>doubleCount2:{{doubleCount2}}</p>
      <button @click="add">提交add的mutation</button>
      <button @click="increment">分发increment的action</button>
      <p>addRootCount:{{addRootCount}}</p>
      <button @click="incrementByRootCount">incrementByRootCount</button>
    </div>
    <script src="vue.js"></script>
    <script src="vuex2.js"></script>
    <script>
      Vue.use(Vuex);
      let counter1 = {
        namespaced: true,
        state:{count:1},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add',undefined,{root:true});
          },
          incrementByRootCount({ state, commit, rootState }){
            commit('add',rootState.count);
          }
        },
        getters:{
          doubleCount1(state){
            return state.count*2;
          },
          addRootCount(state,getters,rootState){
            return state.count+rootState.count;
          }
        }
      }
      let counter2 = {
        namespaced: true,
        state:{count:2},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          }
        },
        getters:{
          doubleCount2(state){
            return state.count*2;
          }
        }
      }
      const store = new Vuex.Store({
        state:{count:10},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          }
        },
        modules:{
          counter1,
          counter2
        }
      });
      var vm = new Vue({
        el:'#app',
        store,
        computed:{
          rootCount(){
            return this.$store.state.count;
          },
          ...Vuex.mapState("counter1", {
            count1:state=>state.count
          }),
          ...Vuex.mapState("counter2", {
            count2:state=>state.count
          }),
          /**
          count1(){
            return this.$store.state.counter1.count;
          },
          count2(){
            return this.$store.state.counter2.count;
          },
          **/
          ...Vuex.mapGetters("counter1", ["doubleCount1"]),
          ...Vuex.mapGetters("counter1", ["addRootCount"]),
          ...Vuex.mapGetters("counter2", ["doubleCount2"]),
           /**
          doubleCount1(){
            return this.$store.getters[`counter1/doubleCount1`];
          },
          addRootCount(){
            return this.$store.getters[`counter1/addRootCount`];
          },
          doubleCount2(){
            return this.$store.getters[`counter2/doubleCount2`];
          },
          **/
        },
        methods:{
          add(){
            this.$store.commit('add');
          },
          ...Vuex.mapActions("counter1", ["increment","incrementByRootCount"]),
          /**
          increment(){
            this.$store.dispatch('counter1/increment');
          },
          incrementByRootCount(){
            this.$store.dispatch('counter1/incrementByRootCount');
          }
          **/
        }
      })
    </script>
  </body>
</html>

const isFunction = val => typeof val === 'function';
const isString = val => typeof val === 'string';
const isPlainObject = val => typeof val === 'object' && Object.getPrototypeOf(val) === Object.prototype;
var Vuex = {
  Store: function ({state,getters,mutations,actions,modules}) {
    this.state = Vue.observable(state);
    this.actions = actions || {};
    this.modules = modules || {};
    this.mutations = mutations || {};
    for (let moduleName in this.modules) {
      this.state[moduleName] = Vue.observable(this.modules[moduleName].state);
    }
    this.dispatch = function (type, payload) {
      let result =  this.actions[type]?.(this, payload);
      for (let moduleName in this.modules) {
        let module = this.modules[moduleName];
        if(module.namespaced){
          let parts = type.split('/');
          if(parts[0]===moduleName){
            const commit = (type,payload,options)=> this.commit(`${moduleName}/${type}`,payload,options);
            module.actions[parts[1]]({...this,rootState:this.state,rootGetters:this.getters,commit}, payload)
          }
        }else{
          module.actions[type]({...this,rootState:this.state}, payload)
        }
      }
      return result;
    };
    this.commit = (type, payload,options) => {
      if (isPlainObject(type)) {
        payload = type;
        type = type.type;
      }
      if(options && options.root){
        type=type.split('/').pop();
      }
      mutations[type]?.(this.state, payload);
      for (let moduleName in this.modules) {
        let module = this.modules[moduleName];
        if(module.namespaced){
          let parts = type.split('/');
          if(parts[0]===moduleName){
            module.mutations[parts[1]](this.state[moduleName], payload,this.state)
          }
        }else{
          module.mutations[type](this.state[moduleName], payload,this.state)
        }
      }
    };
    this.getters = {};
    if (getters) {
      for (const [key, value] of Object.entries(getters)) {
        Object.defineProperty(this.getters, key, {
          get: () => {
            return value(this.state, this.getters);
          }
        });
      }
    }
    for (let moduleName in this.modules) {
      let module = this.modules[moduleName];
      if (module.getters) {
        for (let key in module.getters) {
            const getterKey=`${moduleName}/${key}`;
            Object.defineProperty(this.getters, getterKey, {
                get: () => {
                    return this.modules[moduleName].getters[key]?.(this.state[moduleName], module.getters, this.state, this.getters);
                }
            });
        }
      }
    }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        console.log(this);
        if (this.$options.store) {
          this.$store = this.$options.store;
        } else if (this.$parent) {
          this.$store = this.$parent.$store;
        }
      }
    });
  },
+ mapState(namespace,map) {
+   if(arguments.length===1){
+     map=namespace;
+     namespace='';
+   }
    let computed = {};
    if (Array.isArray(map)) {
      map.forEach(key => {
        computed[key] = function () {
          if(namespace){
            return this.$store.state[namespace][key];
          }else{
            return this.$store.state[key];
          }
        };
      });
    } else {
      for (const [key, value] of Object.entries(map)) {
        if (isFunction(value)) {
          computed[key] = function () {
            if(namespace){
              return value.call(this, this.$store.state[namespace]);
            }else{
              return value.call(this, this.$store.state);
            }

          };
        } else if (isString(value)) {
          computed[key] = function () {
            if(namespace){
              return this.$store.state[namespace][value];
            }else{
              return this.$store.state[value];
            }
          };
        }
      }
    }
    return computed;
  },
+ mapGetters(namespace,getterNames) {
+   if(arguments.length===1){
+     map=namespace;
+     namespace='';
+   }
    let computed = {};
    getterNames.forEach(getterName => {
      computed[getterName] = function () {
        if(namespace){
          return this.$store.getters[namespace+"/"+getterName];
        }else{
          return this.$store.getters[getterName];
        }

      };
    });
    return computed;
  },
+ mapMutations(namespace,mutationNames) {
+   if(arguments.length===1){
+     map=namespace;
+     namespace='';
+   }
    const methods = {};
    mutationNames.forEach(mutationName => {
      methods[mutationName] = function (payload) {
        if(namespace){
          this.$store.commit(namespace+"/"+mutationName, payload);
        }else{
          this.$store.commit(mutationName, payload);
        }

      };
    });
    return methods;
  },
+ mapActions(namespace,actionNames) {
+   if(arguments.length===1){
+     map=namespace;
+     namespace='';
+   }
    const methods = {};
    for (const name of actionNames) {
      methods[name] = function (payload) {
        if(namespace){
          this.$store.dispatch(namespace+"/"+name, payload);
        }else{
          this.$store.dispatch(name, payload);
        }
      };
    }
    return methods;
  }
};

8.4 createNamespacedHelpers #

而且,你可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <p>rootCount:{{rootCount}}</p>
      <p>count1:{{count1}}</p>
      <p>doubleCount1:{{doubleCount1}}</p>
      <p>count2:{{count2}}</p>
      <p>doubleCount2:{{doubleCount2}}</p>
      <button @click="add">提交add的mutation</button>
      <button @click="increment">分发increment的action</button>
      <p>addRootCount:{{addRootCount}}</p>
      <button @click="incrementByRootCount">incrementByRootCount</button>
    </div>
    <script src="vue.js"></script>
    <script src="vuex2.js"></script>
    <script>
      Vue.use(Vuex);
      let counter1 = {
        namespaced: true,
        state:{count:1},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add',undefined,{root:true});
          },
          incrementByRootCount({ state, commit, rootState }){
            commit('add',rootState.count);
          }
        },
        getters:{
          doubleCount1(state){
            return state.count*2;
          },
          addRootCount(state,getters,rootState){
            return state.count+rootState.count;
          }
        }
      }
      let counter2 = {
        namespaced: true,
        state:{count:2},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          }
        },
        getters:{
          doubleCount2(state){
            return state.count*2;
          }
        }
      }
      const store = new Vuex.Store({
        state:{count:10},
        mutations:{
          add(state,payload=1){
            state.count+=payload;
          }
        },
        actions:{
          increment(context){
            context.commit('add');
          }
        },
        modules:{
          counter1,
          counter2
        }
      });
      const { mapState:mapState1, mapGetters:mapGetters1,mapActions:mapActions1 } = Vuex.createNamespacedHelpers('counter1')
      const { mapState:mapState2, mapGetters:mapGetters2 } = Vuex.createNamespacedHelpers('counter2')
      var vm = new Vue({
        el:'#app',
        store,
        computed:{
          rootCount(){
            return this.$store.state.count;
          },
          ...mapState1({
            count1:state=>state.count
          }),
          ...mapState2({
            count2:state=>state.count
          }),
          /**
          count1(){
            return this.$store.state.counter1.count;
          },
          count2(){
            return this.$store.state.counter2.count;
          },
          **/
          ...mapGetters1(["doubleCount1"]),
          ...mapGetters1(["addRootCount"]),
          ...mapGetters2(["doubleCount2"]),
           /**
          doubleCount1(){
            return this.$store.getters[`counter1/doubleCount1`];
          },
          addRootCount(){
            return this.$store.getters[`counter1/addRootCount`];
          },
          doubleCount2(){
            return this.$store.getters[`counter2/doubleCount2`];
          },
          **/
        },
        methods:{
          add(){
            this.$store.commit('add');
          },
          ...mapActions1(["increment","incrementByRootCount"]),
          /**
          increment(){
            this.$store.dispatch('counter1/increment');
          },
          incrementByRootCount(){
            this.$store.dispatch('counter1/incrementByRootCount');
          }
          **/
        }
      })
    </script>
  </body>
</html>

const isFunction = val => typeof val === 'function';
const isString = val => typeof val === 'string';
const isPlainObject = val => typeof val === 'object' && Object.getPrototypeOf(val) === Object.prototype;
var Vuex = {
  Store: function ({state,getters,mutations,actions,modules}) {
    this.state = Vue.observable(state);
    this.actions = actions || {};
    this.modules = modules || {};
    this.mutations = mutations || {};
    for (let moduleName in this.modules) {
      this.state[moduleName] = Vue.observable(this.modules[moduleName].state);
    }
    this.dispatch = function (type, payload) {
      let result =  this.actions[type]?.(this, payload);
      for (let moduleName in this.modules) {
        let module = this.modules[moduleName];
        if(module.namespaced){
          let parts = type.split('/');
          if(parts[0]===moduleName){
            const commit = (type,payload,options)=> this.commit(`${moduleName}/${type}`,payload,options);
            module.actions[parts[1]]({...this,rootState:this.state,rootGetters:this.getters,commit}, payload)
          }
        }else{
          module.actions[type]({...this,rootState:this.state}, payload)
        }
      }
      return result;
    };
    this.commit = (type, payload,options) => {
      if (isPlainObject(type)) {
        payload = type;
        type = type.type;
      }
      if(options && options.root){
        type=type.split('/').pop();
      }
      mutations[type]?.(this.state, payload);
      for (let moduleName in this.modules) {
        let module = this.modules[moduleName];
        if(module.namespaced){
          let parts = type.split('/');
          if(parts[0]===moduleName){
            module.mutations[parts[1]](this.state[moduleName], payload,this.state)
          }
        }else{
          module.mutations[type](this.state[moduleName], payload,this.state)
        }
      }
    };
    this.getters = {};
    if (getters) {
      for (const [key, value] of Object.entries(getters)) {
        Object.defineProperty(this.getters, key, {
          get: () => {
            return value(this.state, this.getters);
          }
        });
      }
    }
    for (let moduleName in this.modules) {
      let module = this.modules[moduleName];
      if (module.getters) {
        for (let key in module.getters) {
            const getterKey=`${moduleName}/${key}`;
            Object.defineProperty(this.getters, getterKey, {
                get: () => {
                    return this.modules[moduleName].getters[key]?.(this.state[moduleName], module.getters, this.state, this.getters);
                }
            });
        }
      }
    }
  },
  install(Vue) {
    Vue.mixin({
      beforeCreate() {
        console.log(this);
        if (this.$options.store) {
          this.$store = this.$options.store;
        } else if (this.$parent) {
          this.$store = this.$parent.$store;
        }
      }
    });
  },
  mapState(namespace,map) {
    if(arguments.length===1){
      map=namespace;
      namespace='';
    }
    let computed = {};
    if (Array.isArray(map)) {
      map.forEach(key => {
        computed[key] = function () {
          if(namespace){
            return this.$store.state[namespace][key];
          }else{
            return this.$store.state[key];
          }
        };
      });
    } else {
      for (const [key, value] of Object.entries(map)) {
        if (isFunction(value)) {
          computed[key] = function () {
            if(namespace){
              return value.call(this, this.$store.state[namespace]);
            }else{
              return value.call(this, this.$store.state);
            }

          };
        } else if (isString(value)) {
          computed[key] = function () {
            if(namespace){
              return this.$store.state[namespace][value];
            }else{
              return this.$store.state[value];
            }
          };
        }
      }
    }
    return computed;
  },
  mapGetters(namespace,getterNames) {
    if(arguments.length===1){
      map=namespace;
      namespace='';
    }
    let computed = {};
    getterNames.forEach(getterName => {
      computed[getterName] = function () {
        if(namespace){
          return this.$store.getters[namespace+"/"+getterName];
        }else{
          return this.$store.getters[getterName];
        }

      };
    });
    return computed;
  },
  mapMutations(namespace,mutationNames) {
    if(arguments.length===1){
      map=namespace;
      namespace='';
    }
    const methods = {};
    mutationNames.forEach(mutationName => {
      methods[mutationName] = function (payload) {
        if(namespace){
          this.$store.commit(namespace+"/"+mutationName, payload);
        }else{
          this.$store.commit(mutationName, payload);
        }

      };
    });
    return methods;
  },
  mapActions(namespace,actionNames) {
    if(arguments.length===1){
      map=namespace;
      namespace='';
    }
    const methods = {};
    for (const name of actionNames) {
      methods[name] = function (payload) {
        if(namespace){
          this.$store.dispatch(namespace+"/"+name, payload);
        }else{
          this.$store.dispatch(name, payload);
        }
      };
    }
    return methods;
  },
+  createNamespacedHelpers(namespace) {
+    return {
+      mapState:(map)=>this.mapState(namespace,map),
+      mapGetters:(map)=>this.mapGetters(namespace,map),
+      mapActions:(map)=>this.mapActions(namespace,map),
+      mapMutations:(map)=>this.mapMutations(namespace,map)
+    }
+ }
};