### 一、介绍modules
Vuex中State使用是单一状态树结构,应该的所有的状态都放在state里面,项目比较复杂,那么state是一个很大的对象,store对象也将对变得非常大,难于管理。
modules:可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。
### 二、modules使用方法
##### 1、最外层 store/index 通过modules引入某个模块的vuex
```
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
// 引入某个模块的vuex
import house from '../pages/xxx/store/index'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
actions,
getters,
modules: {
house
}
});
```
##### 2、模块中store/index导出数据
```
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
export default{
namespaced: true,
state,
mutations,
actions,
getters
}
```
##### 3、模块的命名空间
actions, mutations, getters, 也可以限定在当前模块的命名空间中。需要给我们的模块加一个namespaced 属性
```
export default{
namespaced: true, // 此属性
state,
mutations,
actions,
getters
}
```
当所有的actions, mutations, getters 都被限定到模块的命名空间下,我们dispatch actions, commit mutations 都需要用到命名空间。
##### 4、调用actions
调用某个模块下的actions
```
this.$store.dispatch('get_article_info', this.totalProInfo);
变成
this.$store.dispatch('house/get_article_info', this.totalProInfo);
```
##### 5、使用state
```
...mapState('house', ['trackMessages', 'backendApi'])
或者
this.$store.state.
```
同样getters.xxx 就要变成 getters["house/xxx"]
```
有了命名空间之后,mapState, mapGetters, mapActions 函数也都有了一个参数,用于限定命名空间,每二个参数对象或数组中的属性,都映射到了当前命名空间中。
...mapState("house",{
trackMessages: state => state.trackMessages
})
```