gpt4 book ai didi

nuxt.js - 在 Vuex 状态中访问 Nuxt `$config`

转载 作者:行者123 更新时间:2023-12-04 12:15:49 26 4
gpt4 key购买 nike

根据 Nuxt 文档,我应该可以访问 $config来自我的 vuex 商店:
“使用您的配置值:
然后,您可以使用页面中的上下文在任何地方访问这些值,店铺 、组件和插件使用 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。你可以通过一个 Action 或 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)
}
}

关于nuxt.js - 在 Vuex 状态中访问 Nuxt `$config`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66960906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com