一、什么是modules?
modules是模块的意思。
为什么要在vuex中使用模块呢?
- Vue使用单一状态树,那么也意味着很多状态都会交给Vuex来管理。
- 当应用变得非常复杂时,store对象就有可能变得相当臃肿。
- 所以vuex允许我们将store分割成模块(modules),而每个模块拥有自己的state、mutations、actions、getters等
就像下面这个意思:
modules:{
moduA:{
state:{
},
mutations:{
},
actions:{
},
getters:{
}
}
}
当然了,如果要划分的清晰一点,可以这样做:(在store文件夹下的index.js中)
//创建对象
const moduleA = {
state:{
name:'aaa'
},
mutations:{
updateName(state,payload){
state.name = payload
}
},
actions:{
},
//第一个参数是state,第二个是getters,第三个是根rootstate
getters:{
jianame(state){
return state.name+'1111'
},
jianame2(state,getters){
return getters.jianame +'222'
},
jianame3(state,getters,rootstate){
return getters.jianame2 + rootstate.counter
}
}
}
const store = new Vuex.store({
state:{
counter:'hhhh'
},
mutations:{
},
actions:{
},
getters:{
}
modules:{
a:moduleA
}
})
在使用的组件中:
<template>
<h3>{
{$store.state.a.name}}</h3>
<h2>{
{$store.getters.jianame}}</h2>
<h2>{
{$store.getters.jianame1}}</h2>
<h2>{
{$store.getters.jianame3}}</h2>
<button @click='Updatename'>修改信息</button>
</template>
<script>
export default{
name:'app',
methods:{
Updataname(){
this.$store.commit('updateName','bbb')
}
}
}
</script>
commit提交的内容会先去store中的mutations中找,找不到再到模块中去找。定义函数的时候最好不要同名!
modules里的getters可以像上面那样去使用