【问题标题】:Is it possible to dispatch an action inside Vuex itself when the Vue Instance is initiated?启动 Vue 实例时,是否可以在 Vuex 内部调度一个动作?
【发布时间】:2018-05-31 04:17:18
【问题描述】:

我一直在研究,到目前为止还没有找到答案。现在我有一个包含 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');
}

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

我试图避免从不同文件中分派操作。

【问题讨论】:

    标签: vue.js vuejs2 vuex


    【解决方案1】:

    您可以在 /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
    

    【讨论】:

    • 完美,谢谢。由于无法从我的“/Store/modules/user/index.js”中调用,它仍然可以帮助我保持一切井井有条。
    • 我试过这个,然后调用 store.dispatch() 似乎锁定了我的电子应用程序。
    猜你喜欢
    • 2020-12-31
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多