在 Vuex 状态中访问 Nuxt `$config`

Access Nuxt `$config` within Vuex State

根据 Nuxt 文档,我应该能够从我的 vuex 存储中访问 $config

“使用您的配置值: 然后,您可以通过使用页面中的上下文、store、组件和插件中的 this.$configcontext.$config 来访问这些值。”(强调来自https://nuxtjs.org/docs/2.x/directory-structure/nuxt-config#runtimeconfig)

当我尝试访问我商店中的 $config 时:

export const state = () => (
    {
        // App vital details
        app: {
            name: 'MyApp',
            appVersion: this.$config.appVersion,
            copyright: helpers.getCurrentYear()
        },
    }
)

我在控制台中收到一条错误消息:“无法读取未定义的 属性 '$config'” 如果我尝试使用 context.$config 我会收到错误消息:“未定义上下文”

我知道 $config 在其他方面“有效”,因为我可以使用 $config.appVersion 在我的模板中访问它,但我如何才能在我的商店中正确访问它?

不幸的是,它并没有那么简单——如果不首先传入上下文实例,您就无法从商店访问 $config。您可以通过操作或 nuxtServerInit 轻松完成此操作。

如果您使用的是 SSR:

actions: {
  nuxtServerInit (vuexContext, { $config }) {
    // your code...
  }
}

否则,您可以通过分派从应用内其他地方调用的操作来传递上下文。例如。来自带有 asyncData 的页面:

page-example.vue

asyncData(context) {
  context.store.dispatch('loadInActionExample', { data: 'test', context: context })
}
Your store (index.js or action module)

export const actions = {
  loadInActionExample(context, payload) {
    // payload.context.$config is accessible...
 
    // execute your action and set data
    context.commit('setData', payload.data)
  }
}