如何在 apollo 请求之前初始化 vuex store

How to initialize vuex store before apollo request

当创建我的基础组件时,我发送了商店,但 apollo 在商店之前查询初始化查询,我得到了不正确的查询。

我的商店代码:

import Vuex from 'vuex';

import reportFilter from '../../report-filter/store';
import account from './account-store';

const store = new Vuex.Store({
    strict: process.env.NODE_ENV === 'development',
    state: {
        role: null,
        id: null,        
    },
    mutations: {
        setAccountData(state, { accountData }) {            
            state.role = accountData.role;
            state.id = accountData.id;            
        },
    },

    actions: {
        initialize({ commit }) {
            // TODO: rewrite after GraphQL backend will be released
            commit('setAccountData', { accountData: document.accountData 
          });
        },
    },
});

export default store;

主要组件中提供了我的apollo客户端。

new Vue({
    router,
    store,
    svgxuse,
    provide: apolloProvider.provide(),
    render: h => h(RootLayout),    
    mounted() {
        redirectIfNeeded(this);
    },
}).$mount('#app');

BaseLayout 组件:

import YNavigation from '../../navigation/Navigation.vue';
import YHeader from '../../header/Header.vue';
import YFooter from '../../footer/Footer.vue';

export default {
    data() {
        return {};
    },

    created() {
        this.$store.dispatch('account/initialize');
    },

    components: { YNavigation, YHeader, YFooter },
};

我尝试在创建之前在主 vue 组件中分派商店,但没有帮助。

apollo: {
        data: {
            query: gql`
                query GetDataById($id: ID!) {
                  ${this.$store.state.account.role} {
                    getDataById(id: $id) {
                      id
                      someId
                      name                                           
                     }
                  }
                }
            `,
            update: data => cloneDeep(data.user.getDataById),
            variables() {
                return {
                    id: this.actionData.dataId
                };
            },
            skip() {
                return this.actionData.dataId === undefined;
            },
        },
}

我希望通过某个特定角色获取数据,但出现错误,因为查询字符串中 ${this.$store.state.account.role} return 为 null。

我通过 init store 作为插件函数解决了这个问题

import Vuex from 'vuex';

import reportFilter from '../../report-filter/store';
import account from './account-store';
import user from './user-store';

// called when the store is initialized
const initPlugin = store => {
    store.dispatch('account/initialize');
    store.dispatch('user/initialize');
};

const store = new Vuex.Store({
    strict: process.env.NODE_ENV === 'development',
    state: {
        // Global store
        // This is place for current user data or other global info
    },
    modules: {
        reportFilter,
        account,
        user,
    },
    plugins: [initPlugin],
});

export default store;