1.什么是mutations?
上一篇文章說的getters是為了初步獲取和簡單處理state里面的數據(這里的簡單處理不能改變state里面的數據),Vue的視圖是由數據驅動的,也就是說state里面的數據是動態變化的,那么怎么改變呢,切記在Vuex中store數據改變的唯一方法就是mutation!
通俗的理解mutations,里面裝著一些改變數據方法的集合,這是Veux設計很重要的一點,就是把處理數據邏輯方法全部放在mutations里面,使得數據和視圖分離。
2.怎么用mutations?
mutation結構:每一個mutation都有一個字符串類型的事件類型(type)和回調函數(handler),也可以理解為{type:handler()},這和訂閱發布有點類似。先注冊事件,當觸發響應類型的時候調用handker(),調用type的時候需要用到store.commit方法。
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state) { //注冊時間,type:increment,handler第一個參數是state; // 變更狀態 state.count++}}}) store.commit('increment') //調用type,觸發handler(state) 載荷(payload):簡單的理解就是往handler(stage)中傳參handler(stage,pryload);一般是個對象。
mutations: { increment (state, n) { state.count += n}} store.commit('increment', 10)mutation-types:將常量放在單獨的文件中,方便協作開發。 // mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION' // store.jsimport Vuex from 'vuex'import { SOME_MUTATION } from './mutation-types' const store = new Vuex.Store({ state: { ... }, mutations: { // 我們可以使用 ES2015 風格的計算屬性命名功能來使用一個常量作為函數名 [SOME_MUTATION] (state) { // mutate state }}})commit:提交可以在組件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 輔助函數將組件中的 methods 映射為 store.commit 調用(需要在根節點注入 store)。
import { mapMutations } from 'vuex'export default {methods: { ...mapMutations([ 'increment' // 映射 this.increment() 為 this.$store.commit('increment')]), ...mapMutations({ add: 'increment' // 映射 this.add() 為 this.$store.commit('increment') })}}3.源碼分析
registerMutation:初始化mutation
function registerMutation (store, type, handler, path = []) { //4個參數,store是Store實例,type為mutation的type,handler,path為當前模塊路徑 const entry = store._mutations[type] || (store._mutations[type] = []) //通過type拿到對應的mutation對象數組 entry.push(function wrappedMutationHandler (payload) { //將mutation包裝成函數push到數組中,同時添加載荷payload參數 handler(getNestedState(store.state, path), payload) //通過getNestedState()得到當前的state,同時添加載荷payload參數 }) }
新聞熱點
疑難解答
圖片精選