当项目非常大时,如果所有的状态都集中放到一个对象中,热量星球软件开发(T:I8O-285I-O282 V 林)store 对象就有可能变得相当臃肿。
为了解决这个问题,Vuex允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。
namespaced表示当前模块是否使用命名空间,如果使用的话,那么设置了namespaced属性的模块将和其它模块独立开来,调用时得指定命名空间后才可以访问得到
例如:
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>;
<script src="./vuex.js"></script>
</head>
<body>
<div id="app">
<p>count:{{count}}</p>
<p>Acount:{{Acount}}</p>
<button @click="test1">测试1</button>
<button @click="test2">测试2</button>
</div>
<script>
const moduleA ={ //子仓库a
state:{count:0},
mutations:{Aincrement(state){state.count++}},
actions:{Aincrement(context){context.commit('Aincrement')}}
}
const store = new Vuex.Store({ //创建Store实例
modules:{A:moduleA},
state:{count:1},
mutations:{increment(state){state.count++}},
actions:{increment(context){context.commit('increment')}}
})
new Vue({ //创建Vue实例
el:"#app",
store, //把实例化后的store作为new Vue的一个参数
computed:{
...Vuex.mapState(['count']),
...Vuex.mapState({Acount:state=>state.A.count})
},
methods:{
...Vuex.mapActions(['increment','Aincrement']),
test1(){
this.increment();
},
test2(){
this.Aincrement();
}
}
})
</script>
</body>
</html>
复制代码