# [Nuxt] Nuxt 2 - 多國語系 i18n ###### tags: `Nuxt` `i18n` ## Setup 1. 安裝 [nuxtjs/i18n](https://i18n.nuxtjs.org/):`npm install @nuxtjs/i18n` 2. 建立 `locals/`,每個語系拆成獨立 js 檔,維護上會較方便 ```javascript // locales/tw.js export default { greeting: '歡迎 {year} 年', about: '關於', }; ``` ```javascript // locales/en.js export default { greeting: 'Hello world! {year}', about: 'about', }; ``` 4. 修改 `nuxt.config.js` ```javascript import tw from './locales/tw'; import en from './locales/en'; import es from './locales/es'; export default { modules: ['@nuxtjs/i18n'], i18n: { locales: ['zh-tw', 'en', 'es'], // 有哪些語系 defaultLocale: 'zh-tw', // 預設語系 vueI18n: { fallbackLocale: 'zh-tw', // 找不到時使用哪個語系 messages: { 'zh-tw': tw, en, es, }, }, }, }; ``` ## 使用方式 ### template ```htmlmixed <template> <div> <p>{{ $t("about") }}</p> </div> </template> ``` #### [傳入參數](https://kazupon.github.io/vue-i18n/guide/formatting.html#formatting) ```htmlmixed <template> <div> <p>{{ $t("greeting", { year: "2023" }) }}</p> <!-- 語系為 zh-tw 時會顯示 歡迎 2023 年 --> <!-- 語系為 en 時會顯示 Hello world! 2023 --> </div> </template> ``` ### [NuxtLink](https://i18n.nuxtjs.org/basic-usage/#nuxt-link) #### switchLocalePath 改變目前的語系 ```htmlmixed <template> <div> <NuxtLink :to="switchLocalePath('zh-tw')" >ZH-TW</NuxtLink> <NuxtLink :to="switchLocalePath('en')" >EN</NuxtLink> <NuxtLink :to="switchLocalePath('es')" >ES</NuxtLink> </div> </template> ``` #### localePath 換頁並保留目前設定的語系。若有第二個參數(語系),則在換頁後改變至指定的語系 ```htmlmixed <template> <div> <!-- 切換至 About 頁面,並使用目前設定的語系 --> <NuxtLink :to="localePath('/about')">About</NuxtLink> <!-- 切換至 Index 頁面,並使用 es 語系 --> <NuxtLink :to="localePath('/', 'es')">Index </NuxtLink> </div> </template> ``` #### localeRoute #### localeLocation --- :::info 建立日期:2023-08-10 更新日期:2023-08-10 :::