问题描述
我正在SSR模式下使用Nuxt.js构建Vue.js应用程序.我的项目中有 axios
和 vue-i18n
插件.
I am building Vue.js application using Nuxt.js in SSR mode. I have axios
and vue-i18n
plugins in my project.
nuxt.config.js
:
export default {
mode: 'universal',
// some irrelevant configs
modules: [
'@nuxtjs/axios',
'nuxt-i18n',
],
i18n: {
locales: [
{
code: 'en',
name: 'English',
file: 'en-EN.js'
},
{
code: 'de',
name: 'Deutsch',
file: 'de-DE.js'
}],
defaultLocale: 'en',
vueI18n: {
fallbackLocale: 'en',
},
lazy: true,
langDir: 'locales/',
vuex: {
moduleName: 'i18n',
syncLocale: true,
syncMessages: true,
syncRouteParams: true
},
},
/* Axios module configuration */
axios: {}
}
如您所见,i18n设置为惰性加载.消息是从 locales/en-EN.js
和 locales/de-DE.js
文件中提取的.在文件中,我想向将向我提供消息的backend-api请求. locales/en-EN.js
:
As you see i18n is set to lazy loading. And messages are taken from locales/en-EN.js
and locales/de-DE.js
files. In the files I want to make a request to a backend-api which will serve me messages. locales/en-EN.js
:
export default async function (context) {
return await context.$axios.get('backend-api');
}
但是,当我加载页面时,它说未定义 $ axios
:无法读取未定义的属性'get'
.但是,一旦我开始在各种语言之间切换,应用程序就会收到翻译.因此,我的猜测是,尝试从上下文访问 $ axios
的服务器失败,但是在客户端(浏览器)上它成功了.从Nuxt context
访问 $ axios
模块的正确方法是什么?
However when I load the page it says that $axios
is undefined: Cannot read property 'get' of undefined
. But as soon as I start switching between languages, application receives translations. So my guess is that server while attempting to access $axios
from context fails, but on client (Browser) it succeeds. What is the correct way of accessing $axios
module from Nuxt context
?
推荐答案
所以我想问题是在插入插件( i18n
)期间调用了语言环境文件,所以 axios
在应用上下文中尚不可用.
So I guess the problem is that locale files are called during injection of plugins (i18n
) so axios
is not yet available in the app context.
所以我找到了一种解决方法:
So I have found a workaround:
首先,我已经导入了普通的 axios
(除了nuxt模块之外)
First, I have imported plain axios
(in addition to nuxt module)
npm i axios -S
然后在语言环境文件中,我已将其实例导入导出功能中:
Then in locale files i have imported its instance inside export function:
// en-En.js
export default async function (context) {
// axios is derived directly from lib instead of context
const axios = require('axios').default;
let localeMessages = null
await axios.get(
'backend-api'
).then((result) => {
localeMessages = result.data
}).catch(() => {
localeMessages = {}
});
return localeMessages
}
仍不确定这是否是一种有效的方法,但目前仍然有效
Still not sure whether this is a valid way to do it, but for now it works
这篇关于从自定义.js文件访问应用上下文以获取区域设置消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!