是否可以在 Vue 实例启动时在 Vuex 内部调度一个动作?

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

我一直在研究,但到目前为止还没有找到答案。现在我有一个包含 2 个模块的商店实例,但我们将使用第一个作为示例。

/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
}

现在我有一个操作 requestInformation,在另一个名为 app.vue 的文件上,我这样称呼它.

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

我想知道是否可以 dispatch/make 从 vuex 本身向 requestInformation 发出请求,而不必在文件外部调用它,因此一旦启动全局存储,就会调用 requestInformation .

我试图避免从不同的文件中调度操作。

您可以在 /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,
    }
});

store.dispatch('requestInformation');

export default store