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

JavaScript Vue.js

老丝阿飞

2020-03-23

我正在构建一个多语言的Nuxt Web应用程序。
使用官方文档中的示例(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')
    }

这里url指向/locals/en.json我的Github配置文件中托管的文件。

第3051篇《Nuxt-i18n:如何异步加载消息?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android