【问题标题】:Nuxt-i18n: how to load messages asynchronously?Nuxt-i18n:如何异步加载消息?
【发布时间】:2019-03-07 07:41:47
【问题描述】:

我正在构建一个多语言 Nuxt 网络应用程序。
使用来自官方documentation (Codepen link) 的这个例子,我不想再使用保存我的翻译的本地 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 数据来异步设置 enfr 值?

插件/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')
    }

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

【问题讨论】:

    标签: javascript asynchronous nuxt.js nuxt-i18n


    【解决方案1】:

    您可以在构造函数中直接使用axiosawait

    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
          })
        }
      })
    }
    

    【讨论】:

      【解决方案2】:

      我有一个使用 localise.biz 和交叉获取的解决方案

      首先将async添加到pluginsplugins / 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;
      

      【讨论】:

        【解决方案3】:

        这就是我最终的结果:

            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)
          }
        

        【讨论】:

          猜你喜欢
          • 2019-03-07
          • 2019-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-19
          • 1970-01-01
          • 2011-12-06
          • 2015-04-12
          相关资源
          最近更新 更多