【问题标题】:in Vuex, How to load state and use data from the state when the application loads/renders first ?, I am using nuxt, Vue and Vuex as store在 Vuex 中,如何在应用程序首先加载/渲染时加载状态并使用状态中的数据?,我使用 nuxt、Vue 和 Vuex 作为存储
【发布时间】:2020-05-21 15:42:54
【问题描述】:

我正在尝试将 JSON 文件中的数据加载到 VueX 存储中,但在我尝试手动刷新 VueX 存储之前,状态不会被加载。

我想要实现的是,在应用程序呈现之前,应该用数据加载状态。 就像我访问主页之前一样。

但我在 Vue Devtools 上看到,如果将其设置为录制模式,则应用程序会加载数据。

下面是来自 store/index.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);
  },
};

商店/app.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? 



【问题讨论】:

    标签: vue.js vuex nuxt.js


    【解决方案1】:

    我通常在布局中调用我的商店的init 操作。

    如果为时已晚,我猜你也可以在插件中完成。 您可以在插件中使用context.store

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

    【讨论】:

    • 现在我做,使用插件的方式。但我在两个不同的商店调用 init()。我如何确定首先调用哪个 init 的优先级。
    • 为什么要知道先调用哪个?在初始化插件中,您可以按您的顺序调用它store.dispatch("store1/init"); store.dispatch("store2/init")。但是顺序应该没有区别恕我直言,因为操作是异步执行的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 2019-01-19
    • 2020-07-24
    • 2017-07-30
    • 2018-05-24
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多