Search code examples
vue.jsvuejs2vuex

Vuex: Difference between using an Action vs. handling within component?


I am confused at why actions in Vuex can't just be handled within a component.
Assuming I have a basic store:

store.js

const initialState = () => ({
    overlayText: ''
}) 

const mutations = {
    setOverlayText: (state, payload) => {
        state.overlayText = payload;
    },
}

const actions = {   
    clearOverlay: (context, data) => {
        return axios.get(data.url).then((response) => {
            context.commit('setOverlayText', response);
        });
    },
}

If I want to make an API call and change data based off it like below using a Vuex Action:

Option 1

<button @click="dispatchClearOverlay">Get Data</button>

methods: {
    clearOverlay() {
        this.$store.dispatch('clearOverlay', {
            url: '/api/clear-overlay',
        })
    }
}

what is the difference of just doing it within the component like this?

Option 2

<button @click="clearOverlay">Get Data</button>

methods: {
    clearOverlay() {
        axios.get('api/clear-overlay')
        .then(resp => {
            this.$store.commit('setOverlayText', response);
        })
    }
}

Solution

  • The examples you gave are slightly different in that in Option 1, the only possible value that will get stored in state.overlayText is the response from /api/clear-overlay. But in Option 2, you could pass any arbitrary text when you commit the mutation and that value would be stored in state.overlayText.

    More generally, there are some important differences. Mutations have to be synchronous and Actions can be asynchronous. You can also fire multiple mutations by dispatching a single action (imagine if you frequently needed to call the same three mutations). These two features can help keep your components nice and lean, while centralizing more of the Store logic.

    The Dispatching Actions section of the Actions docs helps illustrate these points.