VUEX-action可以修改state嗎
首先回顧下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ù)中判斷嚴格模式的代碼,如下:
if (store.strict) { enableStrictMode(store) }
當 vuex設置為嚴格模式, 執(zhí)行enableStrictMode函數(shù), 源碼如下:
function enableStrictMode (store) { // $watch 函數(shù)來觀察 state的變化 store._vm.$watch(function () { return this._data.$$state }, () => { // tate變化時,調(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 }) }
當store._committing(this._committing)不為true,就會報出異常。
所以,當不是觸發(fā)mutation來修改state, 就不會執(zhí)行commit函數(shù),也不會執(zhí)行_withcommit函數(shù),this._committing = true不會執(zhí)行,當執(zhí)行 enableStrictMode 時,會執(zhí)行 assert 函數(shù),這時store._committing為false,就會報出異常。
回歸標題action可以修改state嗎
不開啟嚴格模式的情況下可以,但是不提倡。
綜上所述,經(jīng)測試得知可以修改并修改成功,但是嚴格模式下控制臺會拋異常且action是異步的,不方便DevTool 調(diào)試
結語
我們開發(fā)要嚴格按照官方文檔開發(fā),避免不必要的錯誤產(chǎn)生。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue中$emit傳遞多個參(arguments和$event)
本文主要介紹了vue中$emit傳遞多個參(arguments和$event),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02vue實現(xiàn)元素拖動并互換位置的實現(xiàn)代碼
在使用Vue的場景下,需要實現(xiàn)對元素進行拖動交換位置,接下來通過本文給大家介紹vue實現(xiàn)元素拖動并互換位置的實現(xiàn)代碼,需要的朋友可以參考下2023-09-09vue中this.$router.push()路由傳值和獲取的兩種常見方法匯總
這篇文章主要介紹了vue中this.$router.push()路由傳值和獲取的兩種常見方法,本文結合示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12Vue實現(xiàn)項目部署到非根目錄及解決刷新頁面時找不到資源
這篇文章主要介紹了Vue實現(xiàn)項目部署到非根目錄及解決刷新頁面時找不到資源問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03django使用channels2.x實現(xiàn)實時通訊
這篇文章主要介紹了django使用channels2.x實現(xiàn)實時通訊,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11