constructor (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) { //通过浏览器script标签使用vuex时自动安装 install(window.Vue) }
if (process.env.NODE_ENV !== 'production') { //断言一些使用环境,必须使用vue.use(vuex),必须存在Promise,必须使用new操作符 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.`) }
const { plugins = [], strict = false } = options
// 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) //这里会对模块module进行收集 this._modulesNamespaceMap = Object.create(null) this._subscribers = [] this._watcherVM = new Vue()
// bind commit and dispatch to self //将dispatch和commit方法的this指针绑定到store上,防止被修改 const store = this const { dispatch, commit } = this 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
const state = this._modules.root.state
// init root module. // this also recursively registers all sub-modules // and collects all module getters inside this._wrappedGetters //处理的核心,包括处理根module、action、mutation、getters和递归注册子module installModule(this, state, [], this._modules.root)
// initialize the store vm, which is responsible for the reactivity // (also registers _wrappedGetters as computed properties) //也是重点,使用vue实例来保存state和getter resetStoreVM(this, state)
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.`)
//module目录下的module.js export default class Module { constructor (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 const rawState = rawModule.state
// Store the origin module's state this.state = (typeof rawState === 'function' ? rawState() : rawState) || {} } /** 省略 **/ }