Vuex 之 命名空间 namespaced

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'])
    },
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值