vuex---module

一、定义

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}
const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}
const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

二、命名空间

// 默认情况下,模块内部的 getter、action 和 mutation 仍然是注册在全局命名空间的
// 通过添加 namespaced: true 的方式使其成为带命名空间的模块
// 此时,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名
modules: {
    account: {
      namespaced: true,
      state: () => ({ msg: '' }), // -> store.account.msg
      getters: {
        isAdmin () { ... } // -> getters['account/isAdmin']
      },
      actions: {
        login () { ... } // -> dispatch('account/login')
      },
      mutations: {
        login () { ... } // -> commit('account/login')
      },

三、带命名空间的辅助函数

...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
})
...mapActions([
    'some/nested/module/foo', // -> this['some/nested/module/foo']()
    'some/nested/module/bar' // -> this['some/nested/module/bar']()
])

// 将模块的空间名称字符串作为第一个参数传递给辅助函数
...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
})
...mapActions('some/nested/module', [
    'foo', // -> this.foo()
    'bar' // -> this.bar()
])

// 使用createNamespacedHelpers创建基于某个命名空间辅助函数
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
...mapState({
    a: state => state.a,
    b: state => state.b
})
...mapActions([
    'foo',
    'bar'
])

四、模块的添加、删除、判断

// 在store创建之后,你可以使用 store.registerModule 方法注册模块
store.registerModule('myModule', {
  // ...
})
// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
  // ...
})

// 使用store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块

// 通过 store.hasModule(moduleName) 方法检查该模块是否已经被注册到store。嵌套模块应该以数组形式传递模块名

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值