Vuex由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。 因此,Vuex 允许我们将 store 分割成模块(module),每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块。 默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的,这样使得多个模块能够对同一 mutation 或 action 作出响应。如果希望你的模块具有更高的封装度和复用性,此时就用到了命名空间这个概念。
一、命名空间模块
在单个模块中,通过添加 namespaced: true 的方式使其成为带命名空间的模块。
const user = {
namsepaced: true,
state: {
token: null,
},
mutations: { ... },
actions: { ... },
}
二、组件中如何获取带有命名空间的 state 数据 / mutations / actions
state
// 方法一:
this.$store.state.user.token
// 方法二:
...mapState({
token: state => state.user.token || ''
})
mutations
// 方法一:
this.$store.commit('user/setToken', token)
// 方法二:
...mapMutations('user', ['setToken'])
actions
// 方法一:
this.$store.dispatch('user/token')
// 方法二:
...mapActions('user', ['token'])
三、使用 mapState、mapMutations、mapActions 来绑定带命名空间的模块时,我们可以使用 createNamespacedHelpers 创建基于某个命名空间辅助函数,它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapMutations, mapActions } = createNamespacedHelpers('user')
export default {
computed: {
...mapState({
token: state => state.token
})
},
methods: {
...mapMutations(['setToken']),
...mapActions(['logout'])
},
}