Appearance
命名空间
本节目标:理解“命名空间”的核心思路,并能把它用于实际开发或面试表达。 默认情况下,模块内部的
action、mutation和getter是注册在全局命名空间的——这样使得多个模块能够对同一mutation或action作出响应。
如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。例如:
const store = new Vuex.Store({ modules: { account: { namespaced: true,
//模块内容(module assets)
state: () => ({ ... }), //模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
getters: { isAdmin () { ... } // -> getters['account/isAdmin'] }, actions: { login () { ... } // -> dispatch('account/login') }, mutations: { login () { ... } // -> commit('account/login') },
//嵌套模块
modules: { //继承父模块的命名空间
myPage: { state: () => ({ ... }), getters: { profile () { ... } // -> getters['account/profile'] } },
//进一步嵌套命名空间
posts: { namespaced: true,
state: () => ({ ... }), getters: { popular () { ... } // -> getters['account/posts/popular'] } } } } }})启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit。换言之,你在使用模块内容(module assets)时不需要在同一模块内额外添加空间名前缀。更改 namespaced 属性后不需要修改模块内的代码。
