【问题标题】:How to import multiple locale json files in Vue 3 + i18n?如何在 Vue 3 + i18n 中导入多个语言环境 json 文件?
【发布时间】:2022-01-03 15:02:06
【问题描述】:

这是我的代码,可以正常运行:

import { createI18n } from 'vue-i18n'
import messages from './components/json/foo/foo_messages.json'

const app = createApp(App)
installI18n(app)

const i18n = createI18n({
  locale: 'ru',
  messages
})

app
  .use(i18n)
  .use(vuetify)
  .mount('#app')

现在我还需要从./components/json/bar/bar_messages.json 加载消息。我试图这样做:

import { createI18n } from 'vue-i18n'
import foo_msg from './components/json/foo/foo_messages.json'
import bar_msg from './components/json/bar/bar_messages.json'

const app = createApp(App)
installI18n(app)

const i18n = createI18n({
  locale: 'ru',
  messages: {foo_msg, bar_msg}
})

app
  .use(i18n)
  .use(vuetify)
  .mount('#app')

但它没有用。谁能告诉我怎么做?

编辑:这是我的 foo json 文件

{
  "ru": {
    "header": {
      "hello": "Привет"
    }
  },
  "en": {
    "header": {
      "hello": "Hello"
    }
  }
}

这是bar json文件

{
  "ru": {
    "footer": {
      "bye": "Пока"
    }
  },
  "en": {
    "footer": {
      "bye": "Goodbye"
    }
  }
}

【问题讨论】:

  • json 文件长什么样子?
  • @BoussadjraBrahim 请看编辑。
  • @PeterKrebs 这不起作用,因为所有顶级属性(语言标识符)都会覆盖来自不同来源的其他顶级属性...
  • @MichalLevý 再往下看答案。例如recursive object merge。代码总是可以根据需要进行调整,例如保留所有属性等。但无论哪种方式,这都是一个很好的答案。

标签: javascript vue.js vuejs3 vue-i18n


【解决方案1】:

您正在尝试做的事情不是很可扩展。鉴于 i18n JSON 消息的格式,您需要将输入文件合并为如下内容:

{
  "ru": {
    "header": {
      "hello": "Привет"
    },
    "footer": {
      "bye": "Пока"
    }
  },
  "en": {
    "header": {
      "hello": "Hello"
    },
    "footer": {
      "bye": "Goodbye"
    }
  }
}

...这在 JS 中绝对是可能的,但您仍然必须为 main.js 中的每个组件导入 JSON 文件,这既繁琐又容易出错

您是否考虑在您的组件中使用 vue-i18n custom blocks?您甚至可以将翻译保存在外部 JSON 文件中,并使用自定义块,如 <i18n src="./myLang.json"></i18n>

这是更好的方法,但如果你仍然想使用你的方法,这里有一个简单的代码,如何将所有翻译文件(从 JSON 导入的对象)合并到 vue-i18n 可用的单个对象中:

// import foo_msg from './components/json/foo/foo_messages.json'
const foo_msg = {
  "ru": {
    "header": {
      "hello": "Привет"
    }
  },
  "en": {
    "header": {
      "hello": "Hello"
    }
  }
}

// import bar_msg from './components/json/bar/bar_messages.json'
const bar_msg = {
  "ru": {
    "footer": {
      "bye": "Пока"
    }
  },
  "en": {
    "footer": {
      "bye": "Goodbye"
    }
  }
}

const sources = [foo_msg, bar_msg]
const messages = sources.reduce((acc, source) => {
  for(key in source) {
    acc[key] = { ...(acc[key] || {}), ...source[key] }
  }
  return acc
},{})

console.log(messages)

【讨论】:

    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多