Vuex中的Module

什么是Module?

Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块

{
    moduleA: {
        state: {},
        mutation: {},
        action: {},
        getters: {}
    },
    moduleB: {
        state: {},
        mutation: {},
        action: {},
        getters: {}
    }
}

用到Module常见的会遇到命名空间 ,此时commit,dispatch,getters会发现一些变化

举个例子

{
    state: {},
    mutation: {},
    action: {},
    module: {
        moduleA: {
            namespaced: true,
            state: {},
            mutation: {
                add(){}  // 访问时需要 this.$store.commit('moduleA/add')
            }, 
            action: {
                add(){} // 访问时需要 this.$store.dispatch('moduleA/add')
            },
            getters: {
                getState(){} // 访问时需要 this.$store.getters['moduleA/getState']
            }
        }
    }
}

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

{
    state: {},
    mutation: {},
    action: {},
    module: {
        moduleA: {
            namespaced: true,
            state: {},
            mutation: {
                add(){}  // 访问时需要 this.$store.commit('moduleA/add')
            }, 
            action: {
                add(){} // 访问时需要 this.$store.dispatch('moduleA/add')
                addTwo: {
                    root: true,
                    handler(context) {}
                } // 访问时需要this.$store.dispatch('addTwo')
            },
            getters: {
                getState(){} // 访问时需要 this.$store.getters['moduleA/getState']
            }
        }
    }
}

带命名空间的绑定函数

computed: {
  ...mapState({
    a: state => state.moduleA.a
  })
},
methods: {
  ...mapActions([
    'moduleA/add' // -> this['smoduleA/add']()
  ])
}

// 或者
computed: {
  ...mapState('moduleA', {
    a: state => state.a
  })
},
methods: {
  ...mapActions('moduleA', [A
    'add' // -> this.add()
  ])
}

// 或者
import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('moduleA')

export default {
  computed: {
    // 在 `moduleA` 中查找
    ...mapState({
      a: state => state.a
    })
  },
  methods: {
    // 在 `moduleA` 中查找
    ...mapActions([
      'add'
    ])
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值