Vuex源码解析 (二) 对于 Store类 的单独拆分解析

90 阅读1分钟

书接上回

Store类

总述:

  • store 声明了 store 类,以及我们常用的 getters 、 state 、 mutaion 、 action 、commit 、 dispatch 等方法
  • commit 、 dispatch 、 subscribe 、 subscribeAction 都是通过发布订阅的模式来实现的
  • 限制只能通过 mutation 更改 state 则是通过 _withCommit 方法来实现的
  • getter 的缓存是通过 vue 的 computed 属性实现的
  • state 的响应式则是通过 vue 的 data 属性实现的

拆分 constructor

拆分 constructor install初始化

在 class 类中 会实现我们之前说过的 install 方法

    // 重复的我们要避免安装多一次
    if (!Vue && typeof window !== 'undefined' && window.Vue) {
      // Vue.use 插件
      install(window.Vue)
    }

拆分 constructor 数据初始化

    // 解构 plugins 和 strict 选项
    const {
      plugins = [],
      strict = false
    } = options
    
    // 初始化定义 Vuex 里面的所有属性
    // 后续用以判断 是否为 mutation 改变状态的重要属性
    this._committing = false
    // 定义 actions 是一个没有原型链的对象, 纯洁对象
    // 收集所有 action 方法 => { xx : [fn , fn,  ...] }
    this._actions = Object.create(null)
    this._actionSubscribers = []
    // 收集所有 mutation 方法 => { xx : [fn , fn,  ...] }
    // 定义 mutations 是纯对象
    this._mutations = Object.create(null)
    // 收集所有 getter 方法 => { xx : [fn , fn,  ...] }
    this._wrappedGetters = Object.create(null)
    // 定义 modules 集合
    this._modules = new ModuleCollection(options)
    // 收集模块命名空间 用以完成 根据模块区分 state mutation 等功能的 { moduleName : Module }
    this._modulesNamespaceMap = Object.create(null)
    // 收集subscribe 方法 [ fn , fn ...]
    this._subscribers = []
    this._watcherVM = new Vue()
    // getter 缓存
    this._makeLocalGettersCache = Object.create(null)

拆分 constructor dispatch 和 commit 的重写流程

    const store = this
    // 从 this 里解构 commit dispatch
    const { dispatch, commit } = this
    // 重写 dispatch 和 commit 方法
    // dispatch ---  boundDispatch
    // commit --- boundCommit
    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)
    }

拆分 constructor 注册模块,state 和 getter模块

    // 严格模式
    this.strict = strict
    // 拿到 root.state, 缓存 root 状态
    const state = this._modules.root.state


    // 注册模块
    installModule(this, state, [], this._modules.root)


    // 初始化 state 和 getter 【 state 、 getters 响应式变化也是在这里实现的 】
    resetStoreVM(this, state)
    
    // 应用插件
    plugins.forEach(plugin => plugin(this))