這篇文章給大家分享的是有關VUEX-action能否修改state的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
首先回顧下vuex,官網圖如下

Vuex 的 store 中的狀態的唯一方法是提交 mutation(mutation類似于事件且必須是同步函數)
action 提交的是 mutation,而不是直接變更狀態且可以包含任意異步操作(Action通過 store.dispatch 方法觸發)
一幅圖看清只能通過mutation修改state的原因

commit函數源碼如下
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函數的參數fn是修改state的函數,在執行fn函數前,將this._committing置為true,理由是在源代碼的251行resetStoreVM函數中判斷嚴格模式的代碼,如下:
if (store.strict) {
enableStrictMode(store)
}當 vuex設置為嚴格模式, 執行enableStrictMode函數, 源碼如下:
function enableStrictMode (store) {
// $watch 函數來觀察 state的變化
store._vm.$watch(function () { return this._data.$$state }, () => {
// tate變化時,調用 assert函數
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,就會報出異常。
所以,當不是觸發mutation來修改state, 就不會執行commit函數,也不會執行_withcommit函數,this._committing = true不會執行,當執行 enableStrictMode 時,會執行 assert 函數,這時store._committing為false,就會報出異常。
回歸標題action可以修改state嗎
不開啟嚴格模式的情況下可以,但是不提倡。
綜上所述,經測試得知可以修改并修改成功,但是嚴格模式下控制臺會拋異常且action是異步的,不方便DevTool 調試
感謝各位的閱讀!關于“VUEX-action能否修改state”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。