介紹mapActions輔助函數:
Action提交的是Mutation,不能夠直接修改state中的狀態,而Mutations是可以直接修改state中狀態的;
Action是支持異步操作的,而Mutations只能是同步操作。
簡單的:
const mutations = { add(state,val){ state.count++ }, reduce(state, val){ state.count -- } } const actions = { //這里的actionAdd是組件中和所觸發的事件相對應的方法 actionAdd(context){ context.commit('add')//這里的add是mutations中的方法 }, //這里是通過參數結構來簡化代碼。 actionReduce( { commit } ){ commit('reduce') }
Actions接受一個context對象參數,該參數具有和store實例相同的屬性和方法,所以我們可以通過context.commit()提交mutations中的方法,
或者可以通過context.state和context.getters去獲取state和getters。
context作為上下文對象,有共享store實例的屬性和方法的權利,但是切記:context並不是store實例本身。
{ commit } 這里直接把commit為屬性的對象傳過來,簡化代碼。
Action 通過 store.dispatch 方法觸發 add() { this.$store.dispatch('actionAdd') }, reduce() { this.$store.dispatch('actionReduce') } Actions支持同樣的載荷方式和對象進行分發: add() { this.$store.dispatch('actionAdd', { id: 1 }) }, reduce() { this.$store.dispatch({ type: 'actionReduce', id: 2 }) }
actions里對應的方法中第二個參數接受分發是傳遞的值
<button @click = 'countAdd'>+</button> <button @click = 'countReduce'>-</button> -------------------------------------------------------- import { mapState, mapMutations, mapActions } from 'vuex' methods: { //如果名字不同,使用mapActions輔助函數的對象參數 //...mapActions( { add: 'countAdd', reduce: 'countReduce'} ) //當action中的函數名和組件節點的方法名相同的時候,使用mapActions輔助函數的數組參數 ...mapActions( ['countAdd', 'countReduce'] ) }