基于Vuex从零实现本身的Vuez插件-installModule(完结)

在上一节中,咱们已经实现了模块的收集功能,如今就差咱们的最后一步,安装模块...javascript

把子模块中全部的getters/mutations/actions所有安装到store中的state/getters/mutations/actionsjava

那么,咱们来实现一下,这个安装函数数组

  • 首先,咱们须要明确函数的输入,也就是函数须要传入的参数
  1. 要安装哪一个模块 -->rootModule
  2. 安装到哪里-->store
  3. 跟模块收集同样,模块安装也是一个递归的过程,所以咱们须要一个数组来辅助咱们达到目的。
  4. 咱们在把子模块的state安装到root module时,会用到state,虽然咱们能够经过store.state方式进行访问,但为了方便起见,这里仍是直接以参数传入。 由此,咱们肯定了函数须要要传入的参数。
  • 对于mutationsactions来讲,可能存在重名的状况,因此咱们使用数组进行存储,即把同名属性放到数组中
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

相关文章
相关标签/搜索