Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dispatch an action inside Vuex itself when the Vue Instance is initiated?

I've been researching and so far no luck finding the answer. Right now I have a store instance with 2 modules, but we'll be using the first as the example.

/Store/index.js

import Vuex from 'vuex';
Vue.use(Vuex);

const store = new Vuex.Store({
    modules: {
        header: require('./modules/header/index').default,
        current_user: require('./modules/user/index').default,
    }
});

export default store

/Store/modules/user/index.js

const state = {
    information: [],
}

const mutations = {
    setInformation(state, data){
        state.information = data;
    }
}

const getters = {
    getFirstName(state){
        return state.information.first_name;
    },
    getProfileImage(state){
        return state.information.image;
    }
}

const actions = {
    requestInformation({commit}){
        axios.get('/app/account/requestUserInformation').then(response => commit('setInformation', response.data) );
    }
}

export default {
    state,
    mutations,
    getters,
    actions
}

Right now I have an action requestInformation, and on another file named app.vue I'm calling it like so.

created(){
    this.$store.dispatch('requestInformation');
}

I was wondering if it's possible to dispatch/make the request to the requestInformation from vuex itself instead of having to call it outside of the file, so as soon as the global store is initiated the requestInformation would be called.

I'm trying to avoid having to dispatch the actions from different files.

like image 786
Stark Avatar asked Dec 23 '22 11:12

Stark


1 Answers

You can dispatch an action as soon as you create the store in /Store/index.js like this:

import Vuex from 'vuex';
Vue.use(Vuex);

const store = new Vuex.Store({
    modules: {
        header: require('./modules/header/index').default,
        current_user: require('./modules/user/index').default,
    }
});

store.dispatch('requestInformation');

export default store
like image 76
kmc059000 Avatar answered Jan 29 '23 14:01

kmc059000