Vuex是 Vue.js 的状态管理库,用于在应用中管理共享的、全局的状态。Vuex 的核心概念有 state、getter、mutation 和 action。
<body>
<div id="app">
<p>{{ count }}</p>
<p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
Vue.use(Vuex);
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>
在 Vuex 中,state 是存储全局共享状态的地方。每一个 Vuex store 都有自己的 state,state 是一个对象,其中包含了全局的状态数据。通过这个单一状态树,我们可以获取全局的状态,进行状态的更改,并对状态的更改进行响应。
这是一个简单的 Vuex store 的例子:
在这个例子中,我们定义了一个状态 count
,初始值为 0。
要访问状态对象,你可以使用 store.state
:
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
});
console.log(store.state.count);
</script>
</body>
那么我们如何在 Vue 组件中展示状态呢?由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:
<body>
<div id="app">{{count}}</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/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。
然而,这种模式导致组件依赖全局状态单例。在模块化的构建系统中,在每个需要使用 state 的组件中需要频繁地导入,并且在测试组件时需要模拟状态。
Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):
通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。
<body>
<div id="app">{{count}}</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0,
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
count() {
return this.$store.state.count;
},
},
});
</script>
</body>
当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:
<body>
<div id="app">{{count}}</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0,
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
...Vuex.mapState({
count:state=>state.count
})
},
});
</script>
</body>
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数 如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它——无论哪种方式都不是很理想。
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接受 state 作为其第一个参数:
通过属性访问
Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
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>
Getter 也可以接受其他 getter 作为第二个参数:
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
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>
我们可以很容易地在任何组件中使用它:
<body>
<div id="app">
{{doneTodosCount}}
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
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>
注意,getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。
<body>
<div id="app">
{{doneTodosCount}}
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
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>
注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性: 如果你想将一个 getter 属性另取一个名字,使用对象形式:
<body>
<div id="app">
{{doneTodosCount}}
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
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: {
...Vuex.mapGetters(['doneTodosCount'])
}
})
console.log(store.getters.getTodoById(2));
</script>
</body>
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。 Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。 这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数: 你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
});
console.log(store.state.count);
store.commit("increment");
console.log(store.state.count);
</script>
</body>
你可以向 store.commit
传入额外的参数,即 mutation 的 载荷(payload):
在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state,payload) {
state.count+=payload.amount;
},
},
});
console.log(store.state.count);
store.commit("increment",{amount:5});
console.log(store.state.count);
</script>
</body>
一条重要的原则就是要记住 mutation 必须是同步函数。为什么?请参考下面的例子:
mutations: {
someMutation (state) {
api.callAsyncMethod(() => {
state.count++
})
}
}
现在想象,我们正在 debug 一个 app 并且观察 devtool 中的 mutation 日志。每一条 mutation 被记录,devtools 都需要捕捉到前一状态和后一状态的快照。然而,在上面的例子中 mutation 中的异步函数中的回调让这不可能完成:因为当 mutation 触发的时候,回调函数还没有被调用,devtools 不知道什么时候回调函数实际上被调用——实质上任何在回调函数中进行的状态的改变都是不可追踪的。
你可以在组件中使用 this.$store.commit('xxx') 提交 mutation
<body>
<div id="app">
<p>{{count}}</p>
<button @click="increment">+</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state,payload) {
state.count+=payload.amount;
},
},
});
var vm = new Vue({
el:'#app',
store,
computed:{
count(){
return this.$store.state.count;
}
},
methods:{
increment(){
store.commit('increment',{amount:5})
}
}
});
</script>
</body>
或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。
<body>
<div id="app">
<p>{{count}}</p>
<button @click="increment({amount:5})">+</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state, payload) {
state.count += payload.amount;
},
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
...Vuex.mapState(["count"]),
},
methods: {
...Vuex.mapMutations(["increment"]),
},
});
</script>
</body>
Action 类似于 mutation,不同在于:
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
increment(context) {
context.commit("increment");
},
},
});
</script>
</body>
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。
Action 通过 store.dispatch 方法触发:
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
increment(context) {
context.commit("increment");
},
},
});
console.log(store.state.count)
store.dispatch('increment')
console.log(store.state.count)
</script>
</body>
乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:
<body>
<div id="app">
<p>{{count}}</p>
<button @click="increment">increment</button>
<button @click="incrementAsync">incrementAsync</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
increment(context) {
context.commit("increment");
},
incrementAsync(context) {
setTimeout(() => {
context.commit("increment");
}, 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>
或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):
<body>
<div id="app">
<p>{{count}}</p>
<button @click="increment">increment</button>
<button @click="incrementAsync">incrementAsync</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
increment(context) {
context.commit("increment");
},
incrementAsync(context) {
setTimeout(() => {
context.commit("increment");
}, 1000);
},
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
count() {
return this.$store.state.count;
},
},
methods: {
...Vuex.mapActions(['increment','incrementAsync'])
},
});
</script>
</body>
Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?
首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
<body>
<div id="app">
<p>{{count}}</p>
<button @click="change">change</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
},
},
actions: {
increment(context) {
context.commit("increment");
},
decrement(context) {
context.commit("decrement");
},
incrementAsync(context) {
return new Promise((resolve) => {
setTimeout(() => {
context.commit("increment");
resolve();
}, 1000);
});
},
decrementAsync(context) {
return new Promise((resolve) => {
setTimeout(() => {
context.commit("decrement");
resolve();
}, 1000);
});
},
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
count() {
return this.$store.state.count;
},
},
methods: {
change() {
this.$store
.dispatch("incrementAsync")
.then(() => {
console.log("incrementAsync done");
return this.$store.dispatch("decrementAsync");
})
.then(() => {
console.log("decrementAsync done");
});
},
},
});
</script>
</body>
最后,如果我们利用 async / await (opens new window),我们可以如下组合 action:
<body>
<div id="app">
<p>{{count}}</p>
<button @click="change">change</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
},
},
actions: {
increment(context) {
context.commit("increment");
},
decrement(context) {
context.commit("decrement");
},
incrementAsync(context) {
return new Promise((resolve) => {
setTimeout(() => {
context.commit("increment");
resolve();
}, 1000);
});
},
decrementAsync(context) {
return new Promise((resolve) => {
setTimeout(() => {
context.commit("decrement");
resolve();
}, 1000);
});
},
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
count() {
return this.$store.state.count;
},
},
methods: {
async change() {
await this.$store.dispatch("incrementAsync");
console.log("incrementAsync done");
await this.$store.dispatch("decrementAsync");
console.log("decrementAsync done");
},
},
});
</script>
</body>
一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
<body>
<div id="app">
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const counter1 = {
state: () => ({ count: 0 }),
mutations: {},
actions: {},
getters: {},
};
const counter2 = {
state: () => ({ count: 0 }),
mutations: {},
actions: {},
};
const store = new Vuex.Store({
modules: {
counter1,
counter2,
},
});
console.log(store.state.counter1.count);
console.log(store.state.counter2.count);
</script>
</body>
对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象。
<body>
<div id="app">
<p>{{count1}}</p>
<p>{{count2}}</p>
<p>{{doubleCount1}}</p>
<p>{{doubleCount2}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const counter1 = {
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount1(state) {
return state.count * 2;
},
},
actions: {},
};
const counter2 = {
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount2(state) {
return state.count * 2;
},
},
actions: {},
};
const store = new Vuex.Store({
modules: {
counter1,
counter2,
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
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;
},
},
methods: {},
});
</script>
</body>
对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:
对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:
<body>
<div id="app">
<p>{{count1}}</p>
<p>{{count2}}</p>
<p>{{doubleCount1}}</p>
<p>{{doubleCount2}}</p>
<button @click="incrementInAction">incrementInAction</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const counter1 = {
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount1(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("increment");
},
},
};
const counter2 = {
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount2(state, getters, rootState) {
return state.count * 2;
},
},
actions: {},
};
const store = new Vuex.Store({
modules: {
counter1,
counter2,
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
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;
},
},
methods: {
incrementInAction() {
this.$store.dispatch("incrementInAction");
},
},
});
</script>
</body>
默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。
如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。例如:
启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit。换言之,你在使用模块内容(module assets)时不需要在同一模块内额外添加空间名前缀。更改 namespaced 属性后不需要修改模块内的代码
<body>
<div id="app">
<p>{{count1}}</p>
<p>{{count2}}</p>
<p>{{doubleCount1}}</p>
<p>{{doubleCount2}}</p>
<button @click="incrementInAction">incrementInAction</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const counter1 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount1(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("increment");
},
},
};
const counter2 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount2(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("increment");
},
},
};
const store = new Vuex.Store({
modules: {
counter1,
counter2,
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
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'];
},
},
methods: {
incrementInAction() {
this.$store.dispatch("counter1/incrementInAction");
this.$store.dispatch("counter2/incrementInAction");
},
},
});
</script>
</body>
</body>
在带命名空间的模块内访问全局内容(Global Assets) 如果你希望使用全局 state 和 getter,rootState 和 rootGetters 会作为第三和第四参数传入 getter,也会通过 context 对象的属性传入 action。
若需要在全局命名空间内分发 action 或提交 mutation,将 { root: true } 作为第三参数传给 dispatch 或 commit 即可。
<body>
<div id="app">
<p>{{count1}}</p>
<p>{{count2}}</p>
<p>{{doubleCount1}}</p>
<p>{{doubleCount2}}</p>
<p>{{rootName}}</p>
<button @click="incrementInAction">incrementInAction</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const counter1 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount1(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("increment");
},
},
};
const counter2 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount2(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("increment");
},
},
};
const store = new Vuex.Store({
state: () => ({ rootName: "root" }),
mutations: {
changeName(state) {
state.rootName = "newRoot";
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("changeName");
},
},
modules: {
counter1,
counter2,
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
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"];
},
rootName() {
return this.$store.state.rootName;
},
},
methods: {
incrementInAction() {
//this.$store.dispatch("counter1/incrementInAction");
//this.$store.dispatch("counter2/incrementInAction");
this.$store.dispatch("incrementInAction", null, { root: true });
},
},
});
</script>
</body>
在带命名空间的模块注册全局 action
若需要在带命名空间的模块注册全局 action,你可添加 root: true,并将这个 action 的定义放在函数 handler 中。例如:
<body>
<div id="app">
<p>{{count1}}</p>
<p>{{count2}}</p>
<p>{{doubleCount1}}</p>
<p>{{doubleCount2}}</p>
<p>{{rootName}}</p>
<button @click="incrementInAction">incrementInAction</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const counter1 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount1(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction: {
root: true,
handler({ state, commit, rootState }) {
commit("increment");
},
},
},
};
const counter2 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount2(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("increment");
},
},
};
const store = new Vuex.Store({
state: () => ({ rootName: "root" }),
mutations: {
changeName(state) {
state.rootName = "newRoot";
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("changeName");
},
},
modules: {
counter1,
counter2,
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
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"];
},
rootName() {
return this.$store.state.rootName;
},
},
methods: {
incrementInAction() {
//this.$store.dispatch("counter1/incrementInAction");
//this.$store.dispatch("counter2/incrementInAction");
this.$store.dispatch("incrementInAction", null, { root: true });
},
},
});
</script>
</body>
当使用 mapState, mapGetters, mapActions 和 mapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐:
对于这种情况,你可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是上面的例子可以简化为:
<body>
<div id="app">
<p>{{count1}}</p>
<p>{{count2}}</p>
<p>{{doubleCount1}}</p>
<p>{{doubleCount2}}</p>
<p>{{rootName}}</p>
<button @click="incrementInAction">incrementInAction</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const counter1 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount1(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction: {
root: true,
handler({ state, commit, rootState }) {
commit("increment");
},
},
},
};
const counter2 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount2(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("increment");
},
},
};
const store = new Vuex.Store({
state: () => ({ rootName: "root" }),
mutations: {
changeName(state) {
state.rootName = "newRoot";
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("changeName");
},
},
modules: {
counter1,
counter2,
},
});
var vm = new Vue({
el: "#app",
store,
computed: {
...Vuex.mapState("counter1", {
count1:state=>state.count
}),
...Vuex.mapState("counter2", {
count2:state=>state.count
}),
...Vuex.mapGetters("counter1", ["doubleCount1"]),
...Vuex.mapGetters("counter2", ["doubleCount2"]),
...Vuex.mapState({
rootName: (state) => state.rootName,
}),
},
methods: {
incrementInAction() {
//this.$store.dispatch("counter1/incrementInAction");
//this.$store.dispatch("counter2/incrementInAction");
this.$store.dispatch("incrementInAction", null, { root: true });
},
},
});
</script>
</body>
而且,你可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:
<body>
<div id="app">
<p>{{count1}}</p>
<p>{{count2}}</p>
<p>{{doubleCount1}}</p>
<p>{{doubleCount2}}</p>
<p>{{rootName}}</p>
<button @click="incrementInAction">incrementInAction</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
<script>
const counter1 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount1(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction: {
root: true,
handler({ state, commit, rootState }) {
commit("increment");
},
},
},
};
const counter2 = {
namespaced: true,
state: () => ({ count: 1 }),
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount2(state, getters, rootState) {
return state.count * 2;
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("increment");
},
},
};
const store = new Vuex.Store({
state: () => ({ rootName: "root" }),
mutations: {
changeName(state) {
state.rootName = "newRoot";
},
},
actions: {
incrementInAction({ state, commit, rootState }) {
commit("changeName");
},
},
modules: {
counter1,
counter2,
},
});
const { mapState:mapState1, mapGetters:mapGetters1 } = Vuex.createNamespacedHelpers('counter1')
const { mapState:mapState2, mapGetters:mapGetters2 } = Vuex.createNamespacedHelpers('counter2')
var vm = new Vue({
el: "#app",
store,
computed: {
...mapState1({
count1:state=>state.count
}),
...mapState2({
count2:state=>state.count
}),
...mapGetters1(["doubleCount1"]),
...mapGetters2(["doubleCount2"]),
...Vuex.mapState({
rootName: (state) => state.rootName,
}),
},
methods: {
incrementInAction() {
//this.$store.dispatch("counter1/incrementInAction");
//this.$store.dispatch("counter2/incrementInAction");
this.$store.dispatch("incrementInAction", null, { root: true });
},
},
});
</script>
</body>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="vuex.js"></script>
<script>
var store = new Vuex.Store({
state: {
count: 1,
}
});
console.log(store.state.count);
</script>
</body>
var Vuex = {
Store: function ({ state }) {
this.state = state;
}
};
<body>
+ <div id="app">
+ <p>{{count}}</p>
+ </div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="vuex.js"></script>
<script>
var store = new Vuex.Store({
state: {
count: 1,
}
});
+ var vm = new Vue({
+ el: "#app",
+ computed: {
+ count() {
+ return store.state.count;
+ },
+ },
+ });
</script>
</body>
<body>
<div id="app">
<p>{{count}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="vuex.js"></script>
<script>
+ Vue.use(Vuex);
var store = new Vuex.Store({
state: {
count: 1,
}
});
var vm = new Vue({
+ store,
el: "#app",
computed: {
count() {
+ return this.$store.state.count;
},
},
});
</script>
</body>
var Vuex = {
Store: function ({ state }) {
this.state = state;
},
+ install: function (Vue) {
+ Vue.mixin({
+ beforeCreate: function () {
+ if (this.$options.store) {
+ Vue.prototype.$store = this.$options.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>
+ <button @click="increment">+</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="vuex3.js"></script>
<script>
+ Vue.use(Vuex);
var store = new Vuex.Store({
state: {
count: 1,
},
+ mutations: {
+ increment(state) {
+ state.count++;
+ },
+ },
});
var vm = new Vue({
store,
el: "#app",
computed: {
count() {
return this.$store.state.count;
},
},
+ methods: {
+ increment() {
+ this.$store.commit("increment");
+ },
+ },
});
</script>
</body>
</html>
var Vuex = {
+ Store: function ({ state, mutations }) {
this.state = state;
+ this.commit = (type) => {
+ mutations[type](state);
+ };
},
install: function (Vue) {
Vue.mixin({
beforeCreate: function () {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store;
}
}
});
},
};
var Vuex = {
Store: function ({ state, mutations }) {
this.state = state;
+ let vm = new Vue({
+ data: state
+ });
this.commit = (type) => {
mutations[type](state);
};
},
install: function (Vue) {
Vue.mixin({
beforeCreate: function () {
if (this.$options.store) {
Vue.prototype.$store = this.$options.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>
<button @click="increment">+</button>
+ <p>{{doubleCount}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="vuex3.js"></script>
<script>
Vue.use(Vuex);
var store = new Vuex.Store({
state: {
count: 1,
},
mutations: {
increment(state) {
state.count++;
},
},
+ getters: {
+ doubleCount(state) {
+ return state.count * 2;
+ },
+ },
});
var vm = new Vue({
store,
el: "#app",
computed: {
count() {
return this.$store.state.count;
},
+ doubleCount() {
+ return this.$store.getters.doubleCount;
+ },
},
methods: {
increment() {
this.$store.commit("increment");
},
},
});
</script>
</body>
</html>
var Vuex = {
+ Store: function ({ state, mutations,getters }) {
this.state = state;
let vm = new Vue({
data: state,
+ computed: Object.entries(getters).reduce((obj, [key, fn]) => {
+ obj[key] = () => fn(state);
+ return obj;
+ }, {})
});
+ this.getters = vm;
this.commit = (type) => {
mutations[type](state);
};
},
install: function (Vue) {
Vue.mixin({
beforeCreate: function () {
if (this.$options.store) {
Vue.prototype.$store = this.$options.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>
<button @click="increment">+</button>
<p>{{doubleCount}}</p>
+ <button @click="incrementAsync">incrementAsync</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="vuex3.js"></script>
<script>
Vue.use(Vuex);
var store = new Vuex.Store({
state: {
count: 1,
},
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount(state) {
return state.count * 2;
},
},
+ actions: {
+ incrementAsync(context) {
+ setTimeout(() => {
+ context.commit("increment");
+ }, 1000);
+ },
+ },
});
var vm = new Vue({
store,
el: "#app",
computed: {
count() {
return this.$store.state.count;
},
doubleCount() {
return this.$store.getters.doubleCount;
},
},
methods: {
increment() {
this.$store.commit("increment");
},
+ incrementAsync() {
+ this.$store.dispatch("incrementAsync");
+ },
},
});
</script>
</body>
</html>
var Vuex = {
+ Store: function ({ state, mutations, getters, actions }) {
this.state = state;
let vm = new Vue({
data: state,
computed: Object.entries(getters).reduce((obj, [key, fn]) => {
obj[key] = () => fn(state);
return obj;
}, {})
});
this.getters = vm;
this.commit = (type) => {
mutations[type](state);
};
+ this.dispatch = (type) => {
+ return actions[type](this)
+ };
},
install: function (Vue) {
Vue.mixin({
beforeCreate: function () {
if (this.$options.store) {
Vue.prototype.$store = this.$options.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>
<button @click="increment">+</button>
<p>{{doubleCount}}</p>
<button @click="incrementAsync">incrementAsync</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="vuex3.js"></script>
<script>
Vue.use(Vuex);
var store = new Vuex.Store({
state: {
count: 1,
},
mutations: {
increment(state) {
state.count++;
},
},
getters: {
doubleCount(state) {
return state.count * 2;
},
},
actions: {
incrementAsync(context) {
setTimeout(() => {
context.commit("increment");
}, 1000);
},
},
});
var vm = new Vue({
store,
el: "#app",
computed: {
+ ...Vuex.mapState(['count']),
+ ...Vuex.mapGetters(['doubleCount']),
},
methods: {
+ ...Vuex.mapMutations(['increment']),
+ ...Vuex.mapActions(['incrementAsync']),
},
});
</script>
</body>
</html>
var Vuex = {
Store: function ({ state, mutations, getters, actions }) {
this.state = state;
let vm = new Vue({
data: state,
computed: Object.entries(getters).reduce((obj, [key, fn]) => {
obj[key] = () => fn(state);
return obj;
}, {})
});
this.getters = vm;
this.commit = (type) => {
mutations[type](state);
};
this.dispatch = (type) => {
return actions[type](this)
};
},
install: function (Vue) {
Vue.mixin({
beforeCreate: function () {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store;
}
}
});
},
+ mapState,
+ mapGetters,
+ mapMutations,
+ mapActions
};
+function mapState(stateNames) {
+ const res = {};
+ for (const name of stateNames) {
+ res[name] = function () {
+ return this.$store.state[name];
+ }
+ }
+ return res;
+}
+function mapGetters(getterNames) {
+ const res = {};
+ for (const name of getterNames) {
+ res[name] = function () {
+ return this.$store.getters[name];
+ }
+ }
+ return res;
+}
+
+function mapMutations(mutationNames) {
+ const res = {};
+ for (const name of mutationNames) {
+ res[name] = function (...args) {
+ return this.$store.commit(name, ...args);
+ }
+ }
+ return res;
+}
+
+function mapActions(actionNames) {
+ const res = {};
+ for (const name of actionNames) {
+ res[name] = function (...args) {
+ return this.$store.dispatch(name, ...args);
+ }
+ }
+ return res;
+}
<body>
<div id="app">
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script src="2.js"></script>
<script>
Vue.use(Vuex);
let counter1 = {
state: {
count: 1,
}
}
let counter2 = {
state: {
count: 1,
}
}
var store = new Vuex.Store({
modules: {
counter1,
counter2,
},
});
var vm = new Vue({
store,
el: "#app"
});
console.log(vm.$store.state.counter1.count);
console.log(vm.$store.state.counter2.count);
</script>
</body>
var Vuex = {
+ Store: function ({ state, mutations={}, getters={}, actions={},modules={} }) {
+ this.state = { ...state };
+ if (modules) {
+ Object.keys(modules).forEach((moduleName) => {
+ this.state[moduleName] = modules[moduleName].state;
+ });
+ }
let vm = new Vue({
data: this.state,
computed: Object.entries(getters).reduce((obj, [key, fn]) => {
obj[key] = () => fn(this.state);
return obj;
}, {})
});
this.getters = vm;
this.commit = (type) => {
mutations[type](state);
};
this.dispatch = (type) => {
return actions[type](this)
};
},
install: function (Vue) {
Vue.mixin({
beforeCreate: function () {
if (this.$options.store) {
Vue.prototype.$store = this.$options.store;
}
}
});
},
mapState,
mapGetters,
mapMutations,
mapActions
};
function mapState(stateNames) {
const res = {};
for (const name of stateNames) {
res[name] = function () {
return this.$store.state[name];
}
}
return res;
}
function mapGetters(getterNames) {
const res = {};
for (const name of getterNames) {
res[name] = function () {
return this.$store.getters[name];
}
}
return res;
}
function mapMutations(mutationNames) {
const res = {};
for (const name of mutationNames) {
res[name] = function (...args) {
return this.$store.commit(name, ...args);
}
}
return res;
}
function mapActions(actionNames) {
const res = {};
for (const name of actionNames) {
res[name] = function (...args) {
return this.$store.dispatch(name, ...args);
}
}
return res;
}