背景
在最近的一次需求開發過程中,有再次使用到Vuex,在狀態更新這一方面,我始終遵循著官方的“叮囑”,謹記“一定不要在action中修改state,而是要在mutation中修改”;于是我不禁產生了一個疑問:Vuex為什么要給出這個限制,它是基于什么原因呢?帶著這個疑問我查看Vuex的源碼,下面請大家跟著我的腳步,來一起揭開這個問題的面紗。
一起閱讀源碼吧~
1.首先我們可以在src/store.js這個文件的Store類中找到下面這段代碼
// ...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)}// ...上面是Vuex兩個最核心的API:dispatch & commit,它們是分別用來提交action和mutation的
那么既然我們今天的目的是為了“了解為什么不能在action中修改state”,所以我們就先看看mutation是怎樣修改state的,然而mutation是通過commit提交的,所以我們先看一下commit的內部實現
commit&mutation
2.commit方法的核心代碼大致如下:
commit (_type, _payload, _options) { // ... this._withCommit(() => { entry.forEach(function commitIterator (handler) { handler(payload) }) }) // ...}不難看出,Vuex在commit(提交)某種類型的mutation時,會先用_withCommit包裹一下這些mutation,即作為參數傳入_withCommit;那么我們來看看_withCommit的內部實現(ps:這里之所以說”某種類型的mutation“,是因為Vuex的確支持聲明多個同名的mutation,不過前提是它們在不同的namespace下;action同理)
3._withCommit方法的代碼如下:
_withCommit (fn) { const committing = this._committing this._committing = true fn() this._committing = committing }是的,你沒有看錯,它真的只有4行代碼;這里我們注意到有一個標志位_committing,在執行fn前,這個標志位會被置為true,這個點我們先記下,一會兒會用到
4.接下來,我要為大家要介紹的是resetStoreVM這個函數,它的作用是初始化store,它首次被執行是在Store的構造函數中
function resetStoreVM (store, state, hot) { // ... if (store.strict) { enableStrictMode(store) }// ...}在這里有一處需要我們注意:resetStoreVM對strict(是否啟用嚴格模式)做了判斷,這里假設我們啟用嚴格模式,那么就會執行enableStrictMode這個函數,下面繼續來看看它的內部實現
function enableStrictMode (store) { store._vm.$watch(function () { return this._data.$$state }, () => { if (process.env.NODE_ENV !== 'production') { assert(store._committing, `do not mutate vuex store state outside mutation handlers.`) } }, { deep: true, sync: true })}
新聞熱點
疑難解答
圖片精選