Mutation
更改 Vuex 的 store 中的狀態(tài)的唯一方法是提交 mutation泡仗。Vuex 中的 mutation 非常類似于事件:每個(gè) mutation 都有一個(gè)字符串的 事件類型 (type) 和 一個(gè) 回調(diào)函數(shù) (handler)埋虹。這個(gè)回調(diào)函數(shù)就是我們實(shí)際進(jìn)行狀態(tài)更改的地方,并且它會(huì)接受 state 作為第一個(gè)參數(shù):
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 變更狀態(tài)
state.count++
}
}
})
你不能直接調(diào)用一個(gè) mutation handler沮焕。這個(gè)選項(xiàng)更像是事件注冊(cè):“當(dāng)觸發(fā)一個(gè)類型為 increment
的 mutation 時(shí)吨岭,調(diào)用此函數(shù)÷褪鳎”要喚醒一個(gè) mutation handler辣辫,你需要以相應(yīng)的 type 調(diào)用 store.commit 方法:
store.commit('increment')
在大多數(shù)情況下,載荷應(yīng)該是一個(gè)對(duì)象魁巩,這樣可以包含多個(gè)字段并且記錄的 mutation 會(huì)更易讀:
// ...
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
對(duì)象風(fēng)格的提交方式
提交 mutation 的另一種方式是直接使用包含 type
屬性的對(duì)象:
store.commit({
type: 'increment',
amount: 10
})
當(dāng)使用對(duì)象風(fēng)格的提交方式急灭,整個(gè)對(duì)象都作為載荷傳給 mutation 函數(shù),因此 handler 保持不變:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
Mutation 需遵守 Vue 的響應(yīng)規(guī)則
既然 Vuex 的 store 中的狀態(tài)是響應(yīng)式的谷遂,那么當(dāng)我們變更狀態(tài)時(shí)葬馋,監(jiān)視狀態(tài)的 Vue 組件也會(huì)自動(dòng)更新。這也意味著 Vuex 中的 mutation 也需要與使用 Vue 一樣遵守一些注意事項(xiàng):
最好提前在你的 store 中初始化好所有所需屬性。
當(dāng)需要在對(duì)象上添加新屬性時(shí)畴嘶,你應(yīng)該
使用
Vue.set(obj, 'newProp', 123)
, 或者-
以新對(duì)象替換老對(duì)象蛋逾。例如,利用對(duì)象展開運(yùn)算符我們可以這樣寫:
state.obj = { ...state.obj, newProp: 123 }
使用常量替代 Mutation 事件類型
使用常量替代 mutation 事件類型在各種 Flux 實(shí)現(xiàn)中是很常見的模式窗悯。這樣可以使 linter 之類的工具發(fā)揮作用区匣,同時(shí)把這些常量放在單獨(dú)的文件中可以讓你的代碼合作者對(duì)整個(gè) app 包含的 mutation 一目了然:
// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'
// store.js
import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
state: { ... },
mutations: {
// 我們可以使用 ES2015 風(fēng)格的計(jì)算屬性命名功能來(lái)使用一個(gè)常量作為函數(shù)名
[SOME_MUTATION] (state) {
// mutate state
}
}
})
用不用常量取決于你——在需要多人協(xié)作的大型項(xiàng)目中,這會(huì)很有幫助蒋院。但如果你不喜歡亏钩,你完全可以不這樣做。
Mutation 必須是同步函數(shù)
一條重要的原則就是要記住 mutation 必須是同步函數(shù)欺旧。為什么姑丑?請(qǐng)參考下面的例子:
mutations: {
someMutation (state) {
api.callAsyncMethod(() => {
state.count++
})
}
}
現(xiàn)在想象,我們正在 debug 一個(gè) app 并且觀察 devtool 中的 mutation 日志辞友。每一條 mutation 被記錄栅哀,devtools 都需要捕捉到前一狀態(tài)和后一狀態(tài)的快照。然而踏枣,在上面的例子中 mutation 中的異步函數(shù)中的回調(diào)讓這不可能完成:因?yàn)楫?dāng) mutation 觸發(fā)的時(shí)候昌屉,回調(diào)函數(shù)還沒有被調(diào)用,devtools 不知道什么時(shí)候回調(diào)函數(shù)實(shí)際上被調(diào)用——實(shí)質(zhì)上任何在回調(diào)函數(shù)中進(jìn)行的狀態(tài)的改變都是不可追蹤的茵瀑。
在組件中提交 Mutation
你可以在組件中使用 this.$store.commit('xxx')
提交 mutation间驮,或者使用 mapMutations
輔助函數(shù)將組件中的 methods 映射為 store.commit
調(diào)用(需要在根節(jié)點(diǎn)注入 store
)。
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment', // 將 `this.increment()` 映射為 `this.$store.commit('increment')`
// `mapMutations` 也支持載荷:
'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 將 `this.add()` 映射為 `this.$store.commit('increment')`
})
}
}
Action
Action 類似于 mutation马昨,不同在于:
- Action 提交的是 mutation竞帽,而不是直接變更狀態(tài)。
- Action 可以包含任意異步操作鸿捧。
讓我們來(lái)注冊(cè)一個(gè)簡(jiǎn)單的 action:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
Action 函數(shù)接受一個(gè)與 store 實(shí)例具有相同方法和屬性的 context 對(duì)象屹篓,因此你可以調(diào)用 context.commit
提交一個(gè) mutation,或者通過 context.state
和 context.getters
來(lái)獲取 state 和 getters匙奴。當(dāng)我們?cè)谥蠼榻B到 Modules 時(shí)堆巧,你就知道 context 對(duì)象為什么不是 store 實(shí)例本身了。
實(shí)踐中泼菌,我們會(huì)經(jīng)常用到 ES2015 的 參數(shù)解構(gòu) 來(lái)簡(jiǎn)化代碼(特別是我們需要調(diào)用 commit
很多次的時(shí)候):
actions: {
increment ({ commit }) {
commit('increment')
}
}
分發(fā) Action
Action 通過 store.dispatch
方法觸發(fā):
store.dispatch('increment')
乍一眼看上去感覺多此一舉谍肤,我們直接分發(fā) mutation 豈不更方便?實(shí)際上并非如此哗伯,還記得 mutation 必須同步執(zhí)行這個(gè)限制么荒揣?Action 就不受約束!我們可以在 action 內(nèi)部執(zhí)行異步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
Actions 支持同樣的載荷方式和對(duì)象方式進(jìn)行分發(fā):
// 以載荷形式分發(fā)
store.dispatch('incrementAsync', {
amount: 10
})
// 以對(duì)象形式分發(fā)
store.dispatch({
type: 'incrementAsync',
amount: 10
})
來(lái)看一個(gè)更加實(shí)際的購(gòu)物車示例焊刹,涉及到調(diào)用異步 API 和分發(fā)多重 mutation:
actions: {
checkout ({ commit, state }, products) {
// 把當(dāng)前購(gòu)物車的物品備份起來(lái)
const savedCartItems = [...state.cart.added]
// 發(fā)出結(jié)賬請(qǐng)求系任,然后樂觀地清空購(gòu)物車
commit(types.CHECKOUT_REQUEST)
// 購(gòu)物 API 接受一個(gè)成功回調(diào)和一個(gè)失敗回調(diào)
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失敗操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
注意我們正在進(jìn)行一系列的異步操作恳蹲,并且通過提交 mutation 來(lái)記錄 action 產(chǎn)生的副作用(即狀態(tài)變更)。
在組件中分發(fā) Action
你在組件中使用 this.$store.dispatch('xxx')
分發(fā) action,或者使用 mapActions
輔助函數(shù)將組件的 methods 映射為 store.dispatch
調(diào)用(需要先在根節(jié)點(diǎn)注入 store
):
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment', // 將 `this.increment()` 映射為 `this.$store.dispatch('increment')`
// `mapActions` 也支持載荷:
'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 將 `this.add()` 映射為 `this.$store.dispatch('increment')`
})
}
}
組合 Action
Action 通常是異步的,那么如何知道 action 什么時(shí)候結(jié)束呢?更重要的是,我們?nèi)绾尾拍芙M合多個(gè) action唉窃,以處理更加復(fù)雜的異步流程?
首先,你需要明白 store.dispatch
可以處理被觸發(fā)的 action 的處理函數(shù)返回的 Promise,并且 store.dispatch
仍舊返回 Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
現(xiàn)在你可以:
store.dispatch('actionA').then(() => {
// ...
})
在另外一個(gè) action 中也可以:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
最后,如果我們利用 async / await婚脱,我們可以如下組合 action:
// 假設(shè) getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}