vuex的mutations如何傳多個傳參?


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

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

 

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

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

 

3、傳多個參數的寫法:

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

  官網的解釋: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;

  所以,我們可以將參數以對象的方式傳進去,多個屬性就是多個參數了。

// ...
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,
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM