vuex的mutations如何傳多個傳參?

一、不傳參時的寫法(官網例子):spa

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // mutate state
      state.count++
    }
  }
})
store.commit('increment')

 

二、傳一個參數的寫法(官網例子):code

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

 

三、傳多個參數的寫法:對象

  此時參數不能繼續在後面加,後面的參數無效,傳進去的參數爲undefined;blog

  官網的解釋:In most cases, the payload should be an object so that it can contain multiple fields, and the recorded mutation will also be more descriptive;ip

  因此,咱們能夠將參數以對象的方式傳進去,多個屬性就是多個參數了。rem

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount1;
state.count += payload.amount2;
state.count += payload.amount3;
state.count += payload.amount4;
} }
store.commit('increment', {
  amount1: 10,
  amount2: 20,
  amount3: 30,
  amount4: 40,
}
相關文章
相關標籤/搜索