Vuex之module

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。

新建一个js,moduleA:

const state = { moduleMsg: ‘这是模块a的数据’}export default { namespaced: true, state}

要特别注意的是namespaced: true,一定要加,使其成为带命名空间的模块。否则会报错:

[vuex] module namespace not found in mapState(): modulea

我们在store里面注入模块:

import modulea from ‘./moduleA’

export default new Vuex.Store({ state, getters, actions, mutations, modules: { modulea }})

然后组件使用:

{{this.$store.state.modulea.moduleMsg}}

之前有提过,各个辅助函数都会接收一个参数,所以:

…mapState( ‘modulea’, [‘moduleMsg’])

包括mapAction、mapMutation等都是一样的。

在对于很大的项目把vuex分模块是很有必要的,但是真的不应该盲目的去使用。

欢迎关注Coding个人笔记 公众号

猜你喜欢

转载自blog.csdn.net/wade3po/article/details/86749766