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

问题描述 投票:1回答:1

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

/store/index.就是

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.就是

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');
}

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

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

vue.js vuejs2 vuex
1个回答
4
投票

您可以在/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
© www.soinside.com 2019 - 2024. All rights reserved.