在上一节中,咱们已经实现了模块的收集功能,如今就差咱们的最后一步,安装模块...javascript
把子模块中全部的getters/mutations/actions
所有安装到store
中的state/getters/mutations/actions
java
那么,咱们来实现一下,这个安装函数数组
state
安装到root module
时,会用到state
,虽然咱们能够经过store.state
方式进行访问,但为了方便起见,这里仍是直接以参数传入。 由此,咱们肯定了函数须要要传入的参数。mutations
和actions
来讲,可能存在重名的状况,因此咱们使用数组进行存储,即把同名属性放到数组中const installModule = (store,state,path,rootModule)=>{
if(path.length){
let parent = path.slice(0,-1).reduce((state,current)=>{
return state[current]
},state)
// 将state 转变成响应式
Vue.set(parent,path[path.length-1],rootModule.state)
}
let getters = rootModule.raw.getters
if(getters){
forEach(getters,(key,fn)=>{
Obejct.defineProperty(store.getters,key,{
get:()=>{
return fn(rootModule.state)
}
})
})
}
let mutations = rootModule.raw.mutations
if(mutations){
forEach(mutations,(key,fn)=>{
let arr = store.mutations[key]||(store.mutations[key]=[])
arr.push((payload)=>{
fn(store.state,payload)
})
})
}
let actions = rootModule.raw.actions
if(actions){
forEach(actions,(key,fn)=>{
let arr = store.actions[key]||(store.actions[key]=[])
arr.push((payload)=>{
fn(store,payload)
})
})
}
forEach(rootModule.children,(moduleName,module)=>{
installModule(store,state,path.concat(moduleName),module)
})
}
复制代码
由于store.mutaions[key]可能时一个数组,因此,咱们要修改咱们的commit
函数。函数
commit(mutationType,paylod){
this.mutations[mutationType].forEach(fn=>fn(payload))
}
复制代码
同理,对于dispatch
方法也应该做相同处理ui
dispatch(actionType,paylod){
this.actions[actionType].forEach(fn=>fn(payload))
}
复制代码
完结撒花.... 完整代码:this