Bil*_*adj 7 javascript asynchronous nuxt.js nuxt-i18n
我正在构建一个多语言 Nuxt 网络应用程序。
使用官方文档(Codepen链接)中的这个示例,我不再希望使用本地 JSON 文件来保存我的翻译,如以下代码中定义的那样工作:
messages: {
'en': require('~/locales/en.json'), # I want to get this asynchronously from an HTTP URL
'fr': require('~/locales/fr.json') # I want to get this asynchronously from an HTTP URL
}
Run Code Online (Sandbox Code Playgroud)
我想知道有哪些可用的替代方法可以通过从 URL 读取 JSON 数据来设置异步en和fr值?
插件/i18n.js:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
export default ({ app, store }) => {
// Set i18n instance on app
// This way we can use it in middleware and pages asyncData/fetch
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: 'en',
messages: {
'en': require('~/locales/en.json'), # How to get this asynchronously?
'fr': require('~/locales/fr.json') # # How to get this asynchronously?
}
})
app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`
}
return `/${app.i18n.locale}/${link}`
}
}
Run Code Online (Sandbox Code Playgroud)
我试过的:
messages: {
'en': axios.get(url).then((res) => {
return res.data
} ),
'fr': require('~/locales/fr.json')
}
Run Code Online (Sandbox Code Playgroud)
凡url指向/locals/en.json这是对我的Github上的个人资料托管文件。
小智 5
您可以直接在构造函数中使用axioswith await:
export default async ({ app, store }) => {
app.i18n = new VueI18n({ //construction a new VueI18n
locale: store.state.i18n.locale,
fallbackLocale: 'de',
messages: {
'de': await axios.get('http://localhost:3000/lang/de.json').then((res) => {
return res.data
}),
'en': await axios.get('http://localhost:3000/lang/en.json').then((res) => {
return res.data
})
}
})
}
Run Code Online (Sandbox Code Playgroud)
小智 2
我有一个使用localise.biz和 cross-fetch的解决方案
首先添加async到插件plugins / i18n.js功能并添加await到远程翻译调用:
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import getMessages from './localize';
Vue.use(VueI18n);
export default async ({ app, store }) => {
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: 'en',
messages: {
'en': await getMessages('en'),
'fr': await getMessages('fr')
}
});
app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) return `/${link}`;
return `/${app.i18n.locale}/${link}`;
}
}
Run Code Online (Sandbox Code Playgroud)
并创建新函数来获取远程翻译:
import fetch from 'cross-fetch';
const LOCALIZE_API_KEY = 'XXXXXXXXXXX';
const LOCALIZE_URL = 'https://localise.biz/api/export/locale';
const HEADERS = {
'Authorization': `Loco ${LOCALIZE_API_KEY}`
};
const getMessages = async (locale) => {
const res = await fetch(`${LOCALIZE_URL}/${locale}.json`, { headers: HEADERS });
if (res.status >= 400) throw new Error("Bad response from server");
return await res.json();
};
export default getMessages;
Run Code Online (Sandbox Code Playgroud)