关于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'] )

}
原文地址:https://www.cnblogs.com/lhl66/p/8261921.html