簡述是用this.$store.mutations.xxx(xx)方式調用,因從未見過此種調用方式,回來就搜索了一下,查詢結果如下
首先前文:
獲取 state 的方式有兩種,分別是?
this.$store.state.num
?這種直接獲取的方式,以及通過 getter 定義的方式獲取?this.$store.getter.num
。而修改 state 不能直接修改對象或者覆蓋對象的屬性,因為我們遵循的是單一狀態樹的管理原則,不允許通過?
this.$store.state.num = 3
?修改 state。
mutations:
定義的 mutations 對象將掛載到 Store 的 mutations 屬性上。
mutations 的每個屬性都是以方法的形式定義,默認接收一個參數,而這個參數實際上就是 Store 的 state 對象,只有在 mutations 的屬性中直接通過?
state.xxx = xxx
?修改 state。
mutations 的方法也不是直接通過?this.$store.mutations.xxx(xx)
?去調用的,而是通過主動觸發的。
可以打印?this.$store
?查看 Store 的屬性,可以發現, mutations 是以?_mutations
?的私有屬性形式存在的,因此并不能直接調用(不能是指不允許)。
從上面的屬性列表中可以發現?commit
?屬性,而這個屬性是一個 function,用來觸發 mutations 中定義的 mutation,所以可以通過commit方式觸發mutations中定義的方法
另外tips:?
1. commit方法穿參除默認參數state外另一個參數是payload,且payload只支持一個參數
2.?mapMutations :
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)` ])} }
?
一萬個感謝讓我更深入認知到mutations
?