代码之家  ›  专栏  ›  技术社区  ›  Billal Begueradj

nuxt-i18n:如何异步加载消息?

  •  2
  • Billal Begueradj  · 技术社区  · 6 年前

    我正在构建一个多语言的Nuxt Web应用程序。
    使用官方的这个例子 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
        }
    

    我想知道异步设置有哪些可用的替代方法 en fr 通过从URL读取JSON数据来获取值?

    插件/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 指向 /locals/en.json 托管在我的Github配置文件上的文件。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Nicolas Grévin    6 年前

    我有一个解决办法 localise.biz 交叉取

    第一次添加 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;