新聞中心
這篇文章給大家分享的是有關(guān)VUEX-action能否修改state的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
首先回顧下vuex,官網(wǎng)圖如下
Vuex 的 store 中的狀態(tài)的唯一方法是提交 mutation(mutation類似于事件且必須是同步函數(shù))
action 提交的是 mutation,而不是直接變更狀態(tài)且可以包含任意異步操作(Action通過 store.dispatch 方法觸發(fā))
一幅圖看清只能通過mutation修改state的原因
commit函數(shù)源碼如下
commit (_type, _payload, _options) { // check object-style commit const { type, payload, options } = unifyObjectStyle(_type, _payload, _options) const mutation = { type, payload } const entry = this._mutations[type] if (!entry) { if (process.env.NODE_ENV !== 'production') { console.error(`[vuex] unknown mutation type: ${type}`) } return } // 用來修改state this._withCommit(() => { entry.forEach(function commitIterator (handler) { handler(payload) }) }) this._subscribers.forEach(sub => sub(mutation, this.state)) if ( process.env.NODE_ENV !== 'production' && options && options.silent ) { console.warn( `[vuex] mutation type: ${type}. Silent option has been removed. ` + 'Use the filter functionality in the vue-devtools' ) } }
this._withCommit來修改state,其源代碼如下
_withCommit (fn) { const committing = this._committing this._committing = true fn() this._committing = committing }
其中_withCommit函數(shù)的參數(shù)fn是修改state的函數(shù),在執(zhí)行fn函數(shù)前,將this._committing置為true,理由是在源代碼的251行resetStoreVM函數(shù)中判斷嚴(yán)格模式的代碼,如下:
if (store.strict) { enableStrictMode(store) }
當(dāng) vuex設(shè)置為嚴(yán)格模式, 執(zhí)行enableStrictMode函數(shù), 源碼如下:
function enableStrictMode (store) { // $watch 函數(shù)來觀察 state的變化 store._vm.$watch(function () { return this._data.$$state }, () => { // tate變化時(shí),調(diào)用 assert函數(shù) if (process.env.NODE_ENV !== 'production') { // 判斷 store._committing assert(store._committing, `do not mutate vuex store state outside mutation handlers.`) } }, { deep: true, sync: true }) }
當(dāng)store._committing(this._committing)不為true,就會(huì)報(bào)出異常。
所以,當(dāng)不是觸發(fā)mutation來修改state, 就不會(huì)執(zhí)行commit函數(shù),也不會(huì)執(zhí)行_withcommit函數(shù),this._committing = true不會(huì)執(zhí)行,當(dāng)執(zhí)行 enableStrictMode 時(shí),會(huì)執(zhí)行 assert 函數(shù),這時(shí)store._committing為false,就會(huì)報(bào)出異常。
回歸標(biāo)題action可以修改state嗎
不開啟嚴(yán)格模式的情況下可以,但是不提倡。
綜上所述,經(jīng)測(cè)試得知可以修改并修改成功,但是嚴(yán)格模式下控制臺(tái)會(huì)拋異常且action是異步的,不方便DevTool 調(diào)試
感謝各位的閱讀!關(guān)于“VUEX-action能否修改state”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
當(dāng)前名稱:VUEX-action能否修改state-創(chuàng)新互聯(lián)
鏈接分享:http://fisionsoft.com.cn/article/hhehs.html