You are viewing a single comment's thread from:

RE: Nuxt开发指南

in #starnoteyesterday

文档

为 Nuxt 项目提供的 I18n(国际化)模块,由 Vue I18n 驱动。

yarn add @nuxtjs/i18n  //^10.2.0"  10.2.1
// npx nuxi@latest module add @nuxtjs/i18n

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/locales/en.json
{
  "welcome": "Welcome",
  "question": {
    "responsive": "Responsive",
    "contact": "Contact"
  }
}

3. 前端使用
<h1>{{ $t('welcome') }}</h1>
{{ $t('question.responsive') }}
:placeholder="$t('placeholder')"
<script setup> 
  $t('welcome') 
</script>

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

// script中写法
await setLocale("zh") 
//刷新页面
window.location.reload()   

// 注:Nuxt I18n已做持久化了,无需多余操作
if(process.client){
  const DEFAULT_LANG = navigator.language
  console.log(126, "DEFAULT_LANG", DEFAULT_LANG)  // en-US  zh-CN
}