vuex 源码:深入 vuex 之 mutation

2,201 阅读4分钟

前言

vuex 规定更改 state 的唯一方法是提交 mutation,主要是为了能用 devtools 追踪状态变化。

那么,提交 mutation 除了最主要的更改 state,它还做了其它一些什么事情呢,让我们来一探究竟。

注:本次阅读的是 vuex 的 2.0.0 版本,源码请戳 这里

准备

解读前,需了解一些知识:

  1. Vuex Module
  2. Vuex 严格模式
  3. Class 的基本语法 - this 的指向

解读

在解读前先来看看 mutation 的使用方式:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

store.commit('increment')

初步猜测,store 对象的初始化时将 mutation 属性对象保存起来,在使用 commit 提交的时候取出,并将 store 的 state 等状态作为参数传入,最后调用函数。

好像跟没说一样哈哈。当然,我也不知道它还做了哪些事情。开始解读吧......

从构造函数 constructor 开始,依然过滤与 mutation 无关的代码:

constructor (options = {}) {
  this._mutations = Object.create(null)

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

  // init root module.
  installModule(this, state, [], options)
}

mutation 的注册

mutation 的实现主要分两步,一是初始化 install,二是实现 commit 函数。先来看看初始化的 installModule 方法吧。

function installModule (store, rootState, path, module, hot) {
  const {
    mutations
  } = module

  if (mutations) {
    Object.keys(mutations).forEach(key => {
      registerMutation(store, key, mutations[key], path)
    })
  }
}

代码里循环 options 的 mutations,将其作为参数传入 registerMutation 方法,定位到 registerMutation 方法中(自动忽略 path):

function registerMutation (store, type, handler) {
  const entry = store._mutations[type] || (store._mutations[type] = [])
  entry.push(function wrappedMutationHandler (payload) {
    handler(store.state, payload)
  })
}

将 mutations 保存到了 store._mutations 数组里面,这里可能会好奇一下,为什么同一个 type 对应的是一个数组呢,而不是一个函数。为了解释,小小透露一下。在使用了 module 的情况下,模块中不可避免地可能出现多个相同名称的 mutations,当使用 commit 时,多个相同名称的 mutations 会依次触发。

const store = new Vuex.Store({
  // ...
  mutations: {
    addNote () {
      console.log('root addNote')
    }
  },
  modules: {
    a: {
      mutations: {
        addNote () {
          console.log('module a addNote')
        }
      }
    }
  }
})

以上代码,如果调用 commit('addNote') 的话,那么两个 addNote 方法都会执行,所以两个 addNote 方法都是被放到 store._mutations 数组里面的。试想一下,如果不是数组,那么只会执行其中一个 addNote 方法了。

commit 的实现

接下来看 commit 的实现,这个 commit 挺有趣的,为什么要在构造函数里重新赋值一遍呢。其实,这里是 this 默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。具体了解请戳Class 的基本语法 - this 的指向

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

接下来就来看看 commit 的实现,将保存的 store._mutations 数组取出循环执行。需注意的是这个 _withCommit 方法。

commit (type, payload, options) {
  const mutation = { type, payload }
  const entry = this._mutations[type]

  this._withCommit(() => {
    entry.forEach(function commitIterator (handler) {
      handler(payload)
    })
  })
}

再看 _withCommit 方法,乍看一下,这个方法好像没什么作用。

_withCommit (fn) {
  const committing = this._committing
  this._committing = true
  fn()
  this._committing = committing
}

里面有一个 this._committing 变量,搜索了一下,大致了解了它的作用。首先我们知道 vuex 有一个严格模式

默认不开启,所以 this._committing 变量没什么作用。如果手动开启,state 初始化时在 resetStoreVM 方法里有相应的处理。

// enable strict mode for new vm
if (store.strict) {
  enableStrictMode(store)
}

定位到里面的 enableStrictMode 方法一探究竟:

function enableStrictMode (store) {
  store._vm.$watch('state', () => {
    assert(store._committing, `Do not mutate vuex store state outside mutation handlers.`)
  }, { deep: true, sync: true })
}

这里的 store._committing 默认是 false,所以我们直接赋值 state 会 watch 到并抛出错误。只有在刚刚的 _withCommit 方法里将其设置为 true 再赋值,才不会抛出错误。

总结

mutation 在注册的时候,用一个 store._mutations 数组将 module 模块中所有同名的方法都保存起来,在 commit 的时候则将其所有同名的方法取出并执行。

在开启严格模式的情况下进行 commit 提交,vuex 使用 _withCommit 方法来保证状态变更是由 mutation 函数引起的,而其中是用一个 _committing 变量来判断。测试了一下,虽然会抛出错误,但还是能够进行状态变更的,但这样就不能用 devtools 追踪状态变化了。

最后需记住,mutation 只支持同步更新状态。