9

我正在构建一个多语言 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
    }

我想知道通过从 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}`
  }
}

我尝试了什么

messages: {
      'en': axios.get(url).then((res) => {        
         return res.data
        } ),
      'fr': require('~/locales/fr.json')
    }

Whereurl指向/locals/en.json托管在我的 Github 个人资料上的文件。

4

3 回答 3

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
      })
    }
  })
}
于 2020-03-12T09:38:40.750 回答
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}`;
    }
}

并为获取远程翻译创建新功能:

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;
于 2018-10-05T14:39:32.803 回答
0

这就是我最终得到的:

    async asyncData(context){
       // fetch translation for your source
       var translation = await fetch('/translation')
 
       // get locale of current page
       var locale = context.app.i18n.locale
       // set translation for Server Side Rendering
    context.app.i18n.mergeLocaleMessage(locale, translation)
    // save it for use on client side
       return {translation: translation}
     },
    created(){
        // prevent reverting back to not found after hard-loading page.
        this.$i18n.mergeLocaleMessage(this.$i18n.locale, this.translation)
  }
于 2021-03-19T00:48:17.043 回答