Vuex之modules

modules

我们知道如果一个项目非常大的话状态就会非常的多,如果不进行分类处理,所有的状态都维护在一个state里面的话,状态管理就会变得非常的混乱,这样非常不利于项目的后期维护。我们现在前端推崇模块化开发,为的就是提高开发效率和维护效率,避免重复工作。那么vuex是怎么样解决这个问题的呢?
Vuex允许我们将store分隔成模块(module),每个模块拥有自己的state,mutation,action,getter,甚至是嵌套子模块 具体写法如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

const store1 = {
state:{
count:0
},
mutations:{
add(state){
state.count ++;
}
},
actions:{
addAsync ({ commit }) {
setTimeout(()=>{
commit('add');
},2000);
}
}
}

const store2 = {
state:{
count:0
},
mutations:{
add(state){
state.count ++;
}
},
actions:{
addAsync ({ commit }) {
setTimeout(()=>{
commit('add');
},2000);
}
}
}

export default new Vuex.Store({
modules:{
store1,
store2
}
});

请我吃辣条吧~~
-------------本文结束感谢您的阅读-------------