Vuex Actions in Vue

Written by - Saumya

27 July 2020

Vuex Actions in Vue are part of the Store as we have seen in the Vue basics.

From a Vue component in order to dispatch actions, it is as simple as this.

this.$store.dispatch('auth/login_action', user)

However, Vuex provides helper and utilities to do it even in more readable manner. First of all, one has to get the Vuex into the component.

import { mapActions } from 'vuex'

Next is the actual map of the dispatch code to a function call.

methods : {
    ...mapActions({ 
        login : 'auth/login_action'
    })
}

Now, wherever necessary one can call login() which will dispatch the action. The code will look something like calling a function.

login(user)

What is done by mapActions from Vuex is a mapping of login function to this.$store.dispatch( 'auth/login_action', user ). Wherever the login(user) is called, it is actually doing this.$store.dispatch( 'auth/login_action', user ).

// Now both are same

login(user)

this.$store.dispatch('auth/login_action', user)

Happy coding.