Mutation
1. 前言
本文我們將介紹如何使用 mutation
。包括如何定義 mutation、如何觸發 mutation、mapMutations 輔助函數的使用方式。mutation
是更改 Vuex 中 store 數據狀態的唯一方法。在 vuex
的使用過程中,我們需要編寫大量的 mutation
來操作 store 中的數據。所以,學好如何使用 mutation 非常重要。mutation
并不是一個難點,它的使用非常簡單,接下來我們就一步步學習它的使用。
2. 基礎用法
2.1. 定義 mutation
Vuex 中的 mutation 非常類似于事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是我們實際進行狀態更改的地方,并且它會接受 state 作為第一個參數:
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 變更狀態
state.count++
}
}
})
2.2. 觸發 mutation
我們不能直接調用一個 mutation handler。這個選項更像是事件注冊:“當觸發一個類型為 increment 的 mutation 時,調用此函數?!?要喚醒一個 mutation handler,你需要以相應的 type 調用 store.commit 方法:
store.commit('increment')
2.3. 提交載荷(Payload)
你可以向 store.commit 傳入額外的參數,即 mutation 的 載荷(payload):
mutations: {
incrementByCount (state, n) {
state.count = state.count + n
}
}
store.commit('incrementByCount', 10)
在大多數情況下,載荷應該是一個對象,我們通常接收的參數命名為 payload
,這樣可以包含多個字段并且記錄的 mutation 會更易讀:
// 定義 mutation
mutations: {
incrementByCount (state, payload) {
state.count = state.count + payload.count
}
}
// 觸發 mutation
store.commit('incrementByCount', {
count: 10
})
2.3. 對象風格的提交方式
提交 mutation 的另一種方式是直接使用包含 type 屬性的對象:
store.commit({
type: 'incrementByCount',
count: 10
})
當使用對象風格的提交方式,整個對象都作為載荷傳給 mutation 函數,因此 handler 保持不變:
mutations: {
incrementByCount (state, payload) {
state.count = state.count + payload.count
}
}
完整示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<div>購物車數量:{{count}}</div>
<button @click="add">無參 mutation(+1)</button>
<button @click="addTen">攜參 mutation(+10)</button>
<button @click="addByObject">攜帶對象類型的參數 mutation(+5)</button>
<button @click="commitByObject">對象類型提交 mutation(+3)</button>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
<script type="text/javascript">
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
// 無參 mutation
increment(state) {
state.count++
},
// 帶參 mutation
incrementByCount(state, count) {
state.count = state.count + count
},
// 對象類型參數 mutation
incrementByObject(state, payload) {
state.count = state.count + payload.count
},
},
})
var vm = new Vue({
el: '#app',
store,
methods: {
add() {
this.$store.commit('increment')
},
addTen() {
this.$store.commit('incrementByCount', 10)
},
addByObject() {
this.$store.commit('incrementByObject', {
count: 5
})
},
commitByObject() {
this.$store.commit( {
type: 'incrementByObject',
count: 3
})
}
},
computed: {
count() {
return this.$store.state.count
}
}
})
</script>
</html>
代碼解釋
JS 代碼第 9-11 行,定義了一個無參的 mutation,對 state.count + 1。
JS 代碼第 12-14 行,定義一個傳入 Number 類型參數 count 的 mutation,對 state.count + count。
JS 代碼第 16-18 行,定義一個傳入 Object 類型參數 payload 的 mutation,對 state.count + payload.count。
JS 代碼第 26 行,提交 mutation increment。
JS 代碼第 28 行,提交 mutation incrementByCount 并傳入數量 10。
JS 代碼第 31-33 行,提交 mutation incrementByObject 并傳入參數 {count: 5}。
JS 代碼第 36-39 行,以對象的形式提交 mutation incrementByObject。
3. mutation 使用注意事項
3.1. Mutation 需遵守 Vue 的響應規則
既然 Vuex 的 store 中的狀態是響應式的,那么當我們變更狀態時,監視狀態的 Vue 組件也會自動更新。這也意味著 Vuex 中的 mutation 也需要與使用 Vue 一樣遵守以下注意事項:
-
最好提前在你的 store 中初始化好所有所需屬性。
-
當需要在對象上添加新屬性時,你應該:
- 使用 Vue.set (obj, ‘newProp’, 123), 或者
- 以新對象替換老對象。例如,利用對象展開運算符我們可以這樣寫:
state.obj = { ...state.obj, newProp: 123 }
Tips:以新對象替換老對象替換老對象的方式只能修改
state
中的某個屬性,而不能替換整個state
。想要替換整個state
,需要使用 store.replaceState () 的方法:
state.obj = { ...state.obj, newProp: 123 } // OK
state = {...state, name: '123'} // Error
store.replaceState({...state, name: '123'}) // OK
3.2. 使用常量替代 Mutation 事件類型
在日常開發中,我們一般會使用常量替代 mutation 事件類型。這樣可以使 linter 之類的工具發揮作用,同時可以讓你的代碼合作者對整個 app 包含的 mutation 一目了然:
const INCREMENT_COUNT = 'INCREMENT_COUNT'
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
[INCREMENT_COUNT](state) {
state.count++
},
},
})
var vm = new Vue({
el: '#app',
store,
methods: {
add() {
this.$store.commit('INCREMENT_COUNT')
},
}
})
當然,是否使用用常量取決于個人喜好 —— 在需要多人協作的大型項目中,這會很有幫助。但如果你不喜歡,你完全可以不這樣做。
3.3 Mutation 必須是同步函數
一條重要的原則就是要記住 mutation 必須是同步函數。為什么?請參考下面的例子:
mutations: {
someMutation (state) {
api.callAsyncMethod(() => {
state.count++
})
}
}
現在想象,我們正在 debug 一個 app 并且觀察 devtool 中的 mutation 日志。每一條 mutation 被記錄,devtools 都需要捕捉到前一狀態和后一狀態的快照。然而,在上面的例子中 mutation 中的異步函數中的回調讓這不可能完成:因為當 mutation 觸發的時候,回調函數還沒有被調用,devtools 不知道什么時候回調函數實際上被調用 —— 實質上任何在回調函數中進行的狀態的改變都是不可追蹤的。
4 mapMutations 輔助函數
mapMutations 輔助函數幫助我們簡化提交 mutation 的寫法。
4.1 mapMutations 接收數組格式的參數
mapMutations
可以接收一個事件類型 (type) 的數組:
...mapMutations([
// 將 `this.increment()` 映射為 `this.$store.commit('increment')`
'increment'
]),
4.2 mapMutations 接收對象格式的參數
在某些情況,我們需要對 Mutation
中的函數名重命名以避免和組件內部的變量沖突,這時候我們可以使用對象的方式接收參數:
...mapMutations({
[別名]: [Mutation type]
})
// 例:將 `this.add()` 映射為 `this.$store.commit('increment')`
...mapMutations({
add: 'increment'
})
示例:
const INCREMENT_COUNT = 'INCREMENT_COUNT'
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
[INCREMENT_COUNT](state) {
state.count++
},
},
})
var vm = new Vue({
el: '#app',
store,
methods: {
...Vuex.mapMutations([INCREMENT_COUNT]),
...Vuex.mapMutations({
add: INCREMENT_COUNT
})
}
})
5. 小結
本小節我們介紹了如何使用 Mutation
提交事件來修改 state
中的數據。主要知識點有以下幾點:
- 在 store 中定義 Mutation 事件。
- 通過 $store.commit 觸發 Mutation 事件。
- 通過 mapMutations 方法簡化提交 Mutation 的寫法。
其中,使用 Mutation 需要注意以下幾點:- Mutation 必須是一個同步函數。
- Mutation 需遵守 Vue 的響應規則:只能通過 Vue.set 添加 state 中的屬性,只能通過 store.replaceState 替換這個 state。