3

我正在Nuxt+上制作多语言网站Laravel。我希望有一个选项可以在数据库中设置语言环境并将这些语言环境共享到Nuxt前面。可能吗?

我发现Nuxt插件nuxt-i18n看起来不错,但语言环境是在nuxt.config.js文件中设置的,您无法在此文件中设置来自 api 响应的数据。

4

2 回答 2

6

You can use the Lazy-load translations in nuxt-i18n

First, create a structure for languages similar to this:

nuxt-project/
├── lang/
│   ├── en-US.js
│   ├── es-ES.js
│   ├── fr-FR.js
├── nuxt.config.js

Then set the nuxt.config configuration. Note that you need to set lazy: true and the langDir

// nuxt.config.js

['nuxt-i18n', {
  locales: [
    {
      code: 'en',
      file: 'en-US.js'
    },
    {
      code: 'es',
      file: 'es-ES.js'
    },
    {
      code: 'fr',
      file: 'fr-FR.js'
    }
  ],
  lazy: true,
  langDir: 'lang/'
}]

Then, inside the lang files you can call your API and return the json with the translation messages, like this:

// lang/[lang].js

export default (context) => {
  return new Promise(function (resolve) {
    //Call your API and resolve the content here
    resolve({
      //The JSON return from your API
    })
  });
}

You can find more details in the documentation

于 2019-11-27T16:02:22.250 回答
1

基于这个答案:https ://stackoverflow.com/a/62534495/889126

我做了

export default async function (context) {
  // axios is derived directly from lib instead of context
  const axios = require('axios').default;

  let localeMessages = null

  await axios.get(
    'http://127.0.0.1:8000/api/js/lang-km.json'
  ).then((result) => {
    localeMessages = result.data
  }).catch(() => {
    localeMessages = {}
  });

  return localeMessages
}

它正在工作,您可以在控制台和 NuxtJS 应用程序上显示:

在此处输入图像描述

备注:API我响应为JSON字符串,可以使用任何前缀,我只是做了:(/api/js/lang-km.json只是一个名字)

于 2021-02-10T12:24:29.407 回答