Nuxt i18n多国语言模块集成 / 网络研习社#93

i18n.jpg
https://nuxt.com.cn/modules/i18n

i18n是多国语言模块,主要是在前端集成多种语言的。以前的应用倒也集成过英语,但设计起来有些麻烦,再就是用户多是中文,就没去集成了。这一拖,就是好几年过去了。

现在想在项目中集成,比如AIJoe,还是有点国际范比较好呢。找了下,Nuxt i18n模块已经准备好了。

看了下文档,试了下手,不是很复杂。看来要更新项目啰。以下是集成步骤,可以参考:

yarn add @nuxtjs/i18n  //^10.2.0"

1. nuxt.config.ts 配置
export default defineNuxtConfig({
  modules: [ '@nuxtjs/i18n'],
  i18n: {
    defaultLocale: 'zh',
    strategy: 'no_prefix',
    locales: [
      { code: 'en', name: 'English', file: 'en.json' },
      { code: 'zh', name: 'Chinese', file: 'zh.json' }
    ]
  },
})

2. locale 文件
Nuxt I18n 默认从一个(可配置的)目录结构中加载 locale 文件,默认应在 <rootDir>/i18n/locales 下创建这些 locale 文件。
这步是在项目的根目录下创建这个文件夹`i18n`.
 // i18n/locales/en.json
{
  "welcome": "Welcom"
}

3. 前端使用
<h1>{{ $t('welcome') }}</h1>

4. 切换语言
const { locales, setLocale } = useI18n()
<div>
  <button v-for="locale in locales" @click="setLocale(locale.code)">
    {{ locale.name }}
  </button>
  <h1>{{ $t('welcome') }}</h1>
</div>