美文网首页
手把手实现Vuex(二)

手把手实现Vuex(二)

作者: 泰然自若_750f | 来源:发表于2020-07-04 08:01 被阅读0次

    开始

    上一节我们实现了一个简易版的Vuex,对state,actions,mutations,getters 进行了功能的实现。但是没有对modules进行处理,其实modules才是Vuex中最核心并且是最难实现的。

    module

    Vuex 允许我们将 store 分割成大大小小的对象,每个对象也都拥有自己的 state、getter、mutation、action,这个对象我们把它叫做 module(模块),在模块中还可以继续嵌套子模块。

    • state:所有模块中的state中数据最终都会嵌套在一棵树上。类似于如下
    state={
          name:'yxw',
          age:'20',
          moduleA:{
               schoool:'hb',
                moduleC:{
                   other:''
               }
          },
          moduleB:{
                work:''
    
          }
    }
    
    
    • 模块内部的 action、mutation 和 getter 默认可是注册在全局命名空间的,这样使得多个模块能够对同一 mutation 或 action 作出响应。因此在订阅mutation 和action时必须存储在数组中,每次触发,数组中的方法都要执行。
    image

    具体实现

    module的收集(核心)

    具体实现

    /**
     * module 的收集
     */
    
    class ModuleCollection{
         constructor(options){
               //数据存储对象
               this.root={};
               this.register([],options);
    
         }
         /**
          * 注册
          * @param {*} path 注册路径
          * @param {*} rootModule 注册module
          */
         register(path,rootModule){
            let newModule={
                state:rootModule.state, //为了 state合并方便
                _children:{},
                _raw:rootModule //便于取值
          }
          //代表是根
          if(path.length===0)
          {
              this.root=newModule      
          }
          else{
              //this.register(path.concat(key),module); 递归注册前会把module 的名放在 path的位
              //取最后一项就能取到module
              let parent=path.splice(0,-1).reduce((root,cur)=>{
                    return root._children[cur];
              },this.root);
              //挂载
              parent._children[path.length-1]=newModule;
    
          }
          //如果存在子module
          if(rootModule.modules)
          {
             //然后遍历
              forEach(rootModule.modules,(key,module)=>{
                  //递归注册
                  this.register(path.concat(key),module);
    
               })
          }
         }
    
    }
    
    

    module的安装

    将所有module收集后需要对收集到数据进行整理。

    • state数据要合并。
      通过Vue.set(parent,path[path.length-1],rootModule.state),既可以合并,又能使使 module数据成为响应式数据;
    • action 和mutation 中方法订阅(数组)
    /**
     * 安装方法
     * @param {*} store 
     * @param {*} state 
     * @param {*} path 
     * @param {*} rootModule 
     */
    
    const installModules=(store,state,path,rootModule)=>{
        //modules 中的 state 的处理
         if(path.length>0)
         {
             let parent=path.slice(0,-1).reduce((state,cur)=>{
                 return state[cur];
    
             },state);
             //需要将module中的state 置为响应式数据
             Vue.set(parent,path[path.length-1],rootModule.state);
         }
    
        //处理getter
         let getters=rootModule._raw.getters;
         forEach(getters,(name,fn)=>{
    
            Object.defineProperty(store.getters,name,{
                  get(){
                        return fn.call(this,rootModule.state);
                  }
            });
    
         })
         //处理 mutation
    
         let mutations=rootModule._raw.mutations||{};
         forEach(mutations,(name,fn)=>{
                let arr=store.mutations[name] || (store.mutations[name]=[]);
               arr.push((...params)=>{
                   fn.call(this,rootModule.state,...params);
    
               })
         })
    
          //处理 mutation
    
          let actions=rootModule._raw.actions ||{};
          forEach(actions,(type,fn)=>{
                 let arr=store.actions[type] || (store.actions[type]=[]);
                arr.push((...params)=>{
                    fn.call(this,rootModule.state,...params);
     
                })
          })
        //递归安装子modules
        forEach(rootModule._children,(name,module)=>{
              installModules(store,state,path.concat(name),module)
        })
    
    };
    
    

    Store类

     class Store{
        constructor(options)
        {
            
            this._vm=new Vue({
                  data:options.state
            })
            this.mutations={};
            this.getters={};
              this.actions={};
            var modules=new ModuleCollection(options);
            installModules(this,options.state,[],modules.root);
            console.log(this.mutations)
    
        }
        get state(){
           return  this._vm
    
        }
        commit=(name,...params)=>{
          //订阅的方法在数组中
            this.mutations[name].forEach(fn=>{
                  fn(...params)
            })
        
        }
        dispatch=(type,...params)=>{
        //订阅的方法在数组中
            this.actions[type].forEach(fn=>{
                fn(...params)
          })
     
     
        }
    
    }
    
    

    Vuex的安装方法和导出

    上一节已经说明此处不再赘述。

    //安装的方法
    const install=(_Vue)=>{
       Vue=_Vue;
      //为每个组件注入
      Vue.mixin({
            beforeCreate(){
                //说明是根
                if(this.$options && this.$options.store)
                {
                    this.$store=this.$options.store;
    
                }
                else{
                    this.$store=this.$parent && this.$parent.$store;
                }
            }
      })
    }
    export default{
         install,
         Store
    }
    

    结语

    这样Vuex的核心功能已经基本完成,可以在自己项目中将vuex路径更换,看看时候能实现基本功能,当然和真正源码还差之千里,更多功能实现可以看一下vuex的源码。本人前端小白,如有错误,请谅解,欢迎大家批评指正。

    上一篇:
    https://juejin.im/post/5efdd3b45188252e47138a23(掘金)
    [https://www.jianshu.com/p/8dac5b9da6e5]【简书】

    相关文章

      网友评论

          本文标题:手把手实现Vuex(二)

          本文链接:https://www.haomeiwen.com/subject/jrvyqktx.html