關於mapState和mapMutations和mapGetters 和mapActions輔助函數的用法及作用(四)-----mapActions


介紹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'] )

}

 


免責聲明!

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



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