webpack源码

vuex源码简览

2019-03-25  本文已影响0人  小强不是蟑螂啊
1 vuex到底是什么
代码开头就是:global.Vuex = factory();标识传入的全局对象的vuex属性是一个返回执行的返回结果
而factory函数返回的是index对象,代码下图所示:
var index = {
  Store: Store,
  install: install,
  version: '3.1.0',
  mapState: mapState,
  mapMutations: mapMutations,
  mapGetters: mapGetters,
  mapActions: mapActions,
  createNamespacedHelpers: createNamespacedHelpers
};  
return index

说明vuex是一个对象有Store,install一直到createNamespacedHelpers等8个属性,其中version就是版本号了,我们不需要详细研究了,下面我们简单看下其他七个属性

2 install属性

install函数在主要是将在vuex运行前加载vue,并将vue中options参数中的store函数或者属性保存为this.$store

 //vuex的install属性对应的install函数,
 function install (_Vue) {
   if (Vue && _Vue === Vue) {
     {
       console.error(
         '[vuex] already installed. Vue.use(Vuex) should be called only once.'
       );
     }
     return
   }
   Vue = _Vue;
   applyMixin(Vue);
 }
//在vue初始化是注入vuex参数
 function applyMixin (Vue) {
   var version = Number(Vue.version.split('.')[0]);

   if (version >= 2) {
     Vue.mixin({ beforeCreate: vuexInit });
   } else {
     // override init and inject vuex init procedure
     // for 1.x backwards compatibility.
     var _init = Vue.prototype._init;
     Vue.prototype._init = function (options) {
       if ( options === void 0 ) options = {};

       options.init = options.init
         ? [vuexInit].concat(options.init)
         : vuexInit;
       _init.call(this, options);
     };
   }


   function vuexInit () {
     var options = this.$options;
     // store injection
     if (options.store) {
       this.$store = typeof options.store === 'function'
         ? options.store()
         : options.store;
     } else if (options.parent && options.parent.$store) {
       this.$store = options.parent.$store;
     }
   }
 } 

3 module 从Store.module属性中的模块对象开始,然后遍历其中的每个单独的模块,主要定义了_children和state,_rawModule三个属性,分别是传入的参数和其state,
    var Module = function Module (rawModule, runtime) {
    console.log(rawModule,runtime)
  this.runtime = runtime;
  // Store some children item
  this._children = Object.create(null);
  // Store the origin module object which passed by programmer
  this._rawModule = rawModule;
  var rawState = rawModule.state;

  // Store the origin module's state
  this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
};

var prototypeAccessors = { namespaced: { configurable: true } };

prototypeAccessors.namespaced.get = function () {//为_children对象添加子模块
  return !!this._rawModule.namespaced
};
Module.prototype.addChild = function addChild (key, module) {
  this._children[key] = module;
};
Module.prototype.removeChild = function removeChild (key) {//为_children对象删除子模块
  delete this._children[key];
};

Module.prototype.getChild = function getChild (key) {//获取_children对象特定子模块
  return this._children[key]
};

Module.prototype.update = function update (rawModule) {//重置了模块的actions,mutaions,getter
  this._rawModule.namespaced = rawModule.namespaced;
  if (rawModule.actions) {
    this._rawModule.actions = rawModule.actions;
  }
  if (rawModule.mutations) {
    this._rawModule.mutations = rawModule.mutations;
  }
  if (rawModule.getters) {
    this._rawModule.getters = rawModule.getters;
  }
};

Module.prototype.forEachChild = function forEachChild (fn) { //对每个子模块进行操作
  forEachValue(this._children, fn);
};

Module.prototype.forEachGetter = function forEachGetter (fn) { //对每个模块的getters操作
  if (this._rawModule.getters) {
    forEachValue(this._rawModule.getters, fn);
  }
};

Module.prototype.forEachAction = function forEachAction (fn) {//操作每个子模块的actions方法
  if (this._rawModule.actions) {
    forEachValue(this._rawModule.actions, fn);
  }
};

Module.prototype.forEachMutation = function forEachMutation (fn) {//操作每个模块的mutations方法
  if (this._rawModule.mutations) {
    forEachValue(this._rawModule.mutations, fn);
  }
};
4 ModuleCollection module的集合,就是对上面的modules的操作
var ModuleCollection = function ModuleCollection (rawRootModule) {
  this.register([], rawRootModule, false);
};

ModuleCollection.prototype.get = function get (path) {返回module的子集合
  return path.reduce(function (module, key) {
    return module.getChild(key)
  }, this.root)
};

ModuleCollection.prototype.getNamespace = function getNamespace (path) {//获取module的命名空间
  var module = this.root;
  return path.reduce(function (namespace, key) {
    module = module.getChild(key);
    return namespace + (module.namespaced ? key + '/' : '')
  }, '')
};

ModuleCollection.prototype.update = function update$1 (rawRootModule) {//更新module
  update([], this.root, rawRootModule);
};

ModuleCollection.prototype.register = function register (path, rawModule, runtime) {//更新module
    var this$1 = this;
    if ( runtime === void 0 ) runtime = true;
  {
    assertRawModule(path, rawModule);
  }

  var newModule = new Module(rawModule, runtime);
  if (path.length === 0) {
    this.root = newModule;
  } else {
    var parent = this.get(path.slice(0, -1));
    parent.addChild(path[path.length - 1], newModule);
  }

  // register nested modules
  if (rawModule.modules) {
    forEachValue(rawModule.modules, function (rawChildModule, key) {
      this$1.register(path.concat(key), rawChildModule, runtime);
    });
  }
};

ModuleCollection.prototype.unregister = function unregister (path) {
  var parent = this.get(path.slice(0, -1));
  var key = path[path.length - 1];
  if (!parent.getChild(key).runtime) { return }

  parent.removeChild(key);
};
5 store 属性

确保vuex加载,以及一些用法规则警告,设置一些初始化参数和dispatch commit方法绑定到store,初始化module加载插件等,执行获取,更改state,执行action,mutations方法

    var this$1 = this;
    if ( options === void 0 ) options = {};

    // Auto install if it is not done yet and `window` has `Vue`.
    // To allow users to avoid auto-installation in some cases,
    // this code should be placed here. See #731
    if (!Vue && typeof window !== 'undefined' && window.Vue) {
      install(window.Vue);
    }

    {
      assert(Vue, "must call Vue.use(Vuex) before creating a store instance.");
      assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
      assert(this instanceof Store, "store must be called with the new operator.");
    }

    var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
    var strict = options.strict; if ( strict === void 0 ) strict = false;

    // store internal state
    this._committing = false;
    this._actions = Object.create(null);
    this._actionSubscribers = [];
    this._mutations = Object.create(null);
    this._wrappedGetters = Object.create(null);
    this._modules = new ModuleCollection(options);
    this._modulesNamespaceMap = Object.create(null);
    this._subscribers = [];
    this._watcherVM = new Vue();

    // bind commit and dispatch to self
    var store = this;
    var ref = this;
    var dispatch = ref.dispatch;
    var commit = ref.commit;
    this.dispatch = function boundDispatch (type, payload) {
      return dispatch.call(store, type, payload)
    };
    this.commit = function boundCommit (type, payload, options) {
      return commit.call(store, type, payload, options)
    };

    // strict mode
    this.strict = strict;

    var state = this._modules.root.state;

    // init root module.
    // this also recursively registers all sub-modules
    // and collects all module getters inside this._wrappedGetters
    installModule(this, state, [], this._modules.root);//

    // initialize the store vm, which is responsible for the reactivity
    // (also registers _wrappedGetters as computed properties)
    resetStoreVM(this, state); //将state里面的getter设置getter,并将$$state放到vue里面的data里进行监听

    // apply plugins
    plugins.forEach(function (plugin) { return plugin(this$1); });//执行插件

    var useDevtools = options.devtools !== undefined ? options.devtools : Vue.config.devtools;
    if (useDevtools) { //是否用到Vue Devtools插件,然后适配
      devtoolPlugin(this);
    }
  };

  var prototypeAccessors$1 = { state: { configurable: true } };

  prototypeAccessors$1.state.get = function () { //获取state
    return this._vm._data.$$state
  };

  prototypeAccessors$1.state.set = function (v) {//不能直接修改state
    {
      assert(false, "use store.replaceState() to explicit replace store state.");
    }
  };

  Store.prototype.commit = function commit (_type, _payload, _options) {//执行commit方法
      var this$1 = this;

    // check object-style commit
    var ref = unifyObjectStyle(_type, _payload, _options);
      var type = ref.type;
      var payload = ref.payload;
      var options = ref.options;

    var mutation = { type: type, payload: payload };
    var entry = this._mutations[type];
    if (!entry) {
      {
        console.error(("[vuex] unknown mutation type: " + type));
      }
      return
    }
    this._withCommit(function () {
      entry.forEach(function commitIterator (handler) {
        handler(payload);
      });
    });
    this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); });

    if (
      options && options.silent
    ) {
      console.warn(
        "[vuex] mutation type: " + type + ". Silent option has been removed. " +
        'Use the filter functionality in the vue-devtools'
      );
    }
  };

  Store.prototype.dispatch = function dispatch (_type, _payload) {//触发dispath方法,
      var this$1 = this;

    // check object-style dispatch
    var ref = unifyObjectStyle(_type, _payload);
      var type = ref.type;
      var payload = ref.payload;

    var action = { type: type, payload: payload };
    var entry = this._actions[type];
    if (!entry) {
      {
        console.error(("[vuex] unknown action type: " + type));
      }
      return
    }

    try {
      this._actionSubscribers
        .filter(function (sub) { return sub.before; })
        .forEach(function (sub) { return sub.before(action, this$1.state); });//调用action运行前的before方法
    } catch (e) {
      {
        console.warn("[vuex] error in before action subscribers: ");
        console.error(e);
      }
    }

    var result = entry.length > 1
      ? Promise.all(entry.map(function (handler) { return handler(payload); }))//执行promise
      : entry[0](payload);

    return result.then(function (res) {
      try {
        this$1._actionSubscribers
          .filter(function (sub) { return sub.after; })
          .forEach(function (sub) { return sub.after(action, this$1.state); });//调用action运行后的after方法
      } catch (e) {
        {
          console.warn("[vuex] error in after action subscribers: ");
          console.error(e);
        }
      }
      return res
    })
  };

  Store.prototype.subscribe = function subscribe (fn) { //删除action方法数组中的fn
    return genericSubscribe(fn, this._subscribers)
  };

  Store.prototype.subscribeAction = function subscribeAction (fn) {//mutation方法中的fn
    var subs = typeof fn === 'function' ? { before: fn } : fn;
    return genericSubscribe(subs, this._actionSubscribers)
  };

  Store.prototype.watch = function watch (getter, cb, options) {//监听函数
      var this$1 = this;

    {
      assert(typeof getter === 'function', "store.watch only accepts a function.");
    }
    return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options)
  };

  Store.prototype.replaceState = function replaceState (state) {//重置state
      var this$1 = this;

    this._withCommit(function () {
      this$1._vm._data.$$state = state;//vuex中的state被设置为_vm.data.$$state中
    });
  };

  Store.prototype.registerModule = function registerModule (path, rawModule, options) {
      if ( options === void 0 ) options = {};

    if (typeof path === 'string') { path = [path]; }

    {
      assert(Array.isArray(path), "module path must be a string or an Array.");
      assert(path.length > 0, 'cannot register the root module by using registerModule.');
    }

    this._modules.register(path, rawModule);
    installModule(this, this.state, path, this._modules.get(path), options.preserveState);
    // reset store to update getters...
    resetStoreVM(this, this.state);
  };

  Store.prototype.unregisterModule = function unregisterModule (path) {//删除module
      var this$1 = this;

    if (typeof path === 'string') { path = [path]; }

    {
      assert(Array.isArray(path), "module path must be a string or an Array.");
    }

    this._modules.unregister(path);
    this._withCommit(function () {
      var parentState = getNestedState(this$1.state, path.slice(0, -1));
      Vue.delete(parentState, path[path.length - 1]);
    });
    resetStore(this);
  };

  Store.prototype.hotUpdate = function hotUpdate (newOptions) { //更新module,重置store
    this._modules.update(newOptions);
    resetStore(this, true);
  };

  Store.prototype._withCommit = function _withCommit (fn) {//执行函数
    var committing = this._committing;
    this._committing = true;
    fn();
    this._committing = committing;
  };  

6 mapState

在vue里获取辅助函数获取多个state值的映射

7mapMutations

简化代码执行mutations的辅助函数,第一个参数可以使模块的路径,该路径为上下文,执行后面的模块里的mutations方法

8mapGetters

store 中的 getter 映射到局部计算属性

9 mapActions

mapState 和mapMutations类似,执行的是actions方法

9 createNamespacedHelpers

为一个特定的命名空间,返回mapState,mapMutations,mapGetters,mapMutations的对象集合

总结

vuex是将Store实例注入到Vue的_init初始化过程或者beforeCreated周期函数上调用,将vue.$store绑定store的实例,创建vue的实例vm,将state放在vm的data中的$$state进行监听,这也就是所有的vue实例上getter,action,mutation都是一样的,只要修改state,所有的vue实例都可以获取到修改后的state,

上一篇下一篇

猜你喜欢

热点阅读