в Vuex, Как загрузить состояние и использовать данные из состояния, когда приложение загружает / отображает первым? Я использую nuxt, Vue и Vuex в качестве хранилища - PullRequest
0 голосов
/ 05 февраля 2020

Я пытаюсь загрузить данные из файла JSON в хранилище VueX, но состояние не загружается, пока я не попытаюсь обновить sh хранилище VueX вручную.

Я пытаюсь добиться того, чтобы перед рендерингом приложения было загружено состояние с данными. Как и прежде, чем я получаю доступ к домашней странице.

Но я вижу на Vue Devtools, что если установить его в режим записи, то приложение загружает данные.

Ниже приведен код из магазина / индекса. js

//store/index.js
const exec = (method, { rootState, dispatch }, app) => {
  const dispatches = [];
  Object.keys(rootState).forEach(async (s) => {
    dispatches.push(await dispatch(`${s}/${method}`, app));
  });
  return dispatches;
};

export const actions = {
  nuxtServerInit(store, ctx) {
    console.log('nuxtServerInit');
    exec('init', store, ctx);
  },
  nuxtClientInit(store, ctx) {
    console.log('nuxtClientInit');
    exec('init', store, ctx);
  },
  init(store, ctx) {
    console.log('nuxtInit');
    exec('init', store, ctx);
  },
};

магазина / приложения. js

//store/app.js
export const state = () => ({
  config: {},
});

export const mutations = {
  SET_CONFIG(state, config) {
    state.config = config;
    }
  }
};

export const getters = {
  config: (state) => state.config,
};

const loadConfig = ({ commit  }) => {
  const siteConfig = require('../config/data.json');
  const appConfig = JSON.parse(JSON.stringify(siteConfig.properties));
  commit('SET_CONFIG', appConfig);
};

export const actions = {
  init(store, ctx) {
    loadConfig(store);
  },
};

Here the state is empty when the app loads. How can I access that when the app loads? 



1 Ответ

1 голос
/ 05 февраля 2020

Я обычно называю действие init моего магазина в макете.

Когда это слишком поздно, я думаю, вы также можете сделать это в плагине. Вы можете использовать context.store в плагине.

// plugins/init.js
export default ({ store }) => {
    store.dispatch("init")
}
// store/index.js
export actions = {
  init(context) {
    // ...
  }
}
...