Copyright © 2008 ~ 2024 MUKI space* / omegaBook theme All Rights Reserved.

書接上回

上次提到如何用 Nuxt.js 串接 data 做下拉式選單,接下來會繼續沿用該資料,並將之改寫為多國語系。

安裝 i18n

先來 i18n 一下:

$ npm install @nuxtjs/i18n

nuxt.config.js 設定 i18n 的資料:

modules: [
  '@nuxtjs/i18n',
],
i18n: {
  locales: ['tw', 'en'],
  // 如果環境沒有設定語系,預設為 tw 語言
  defaultLocale: process.env.VUE_APP_I18N_LOCALE || 'tw',
}

你可能會看到另外一種寫法,是直接在 nuxt.config.js 設定語系的資料夾和檔案:

i18n: {
  locales: ['tw', 'en'],
  defaultLocale: process.env.VUE_APP_I18N_LOCALE || 'tw',
  langDir: '~/locales/',
  locales: [ 
    { code: 'en', iso: 'en-EN', file: 'en.json', },
    { code: 'tw', iso: 'zh-TW', file: 'tw.json', },
  ],
},

但我的語系拆的很細,一個 component 會載入一個語系,所以會將語法寫在 components 檔案中。

準備語系檔

參考上一篇 navData 的資料,將他複製起來另存為 json 檔,記得 en 的語系也要準備喔。

[
  {
    "name": "首頁",
    "path": "/"
  },
  {
    "name": "產品",
    "path": "#",
    "children": [
       {
         "name": "產品一",
         "path": "/product/product1",
       },
       {
         "name": "產品二",
         "path": "/product/product2",
       }
    ]
  }
]

改接多國語系

打開 navBar.vue,將之前寫的 fethData 整個刪除,然後加入 i18n 的設定:

i18n: {
  messages: {
    en: require("~/locales/en/nav.json"),
    tw: require("~/locales/tw/nav.json"),
  }
}

接下來在 computed 裡,把 i18n 的語系檔寫回 navData

computed: {
  navData() {
    if (this.$i18n && this.$i18n.messages) {
      return this.$i18n.messages[this.$i18n.locale];
    } else return [];
  },
}

取名為 navData 是因為之前的 data 宣告了 navData 這個物件,因此只要修改 js code 即可,不用改上方 template 的 v-for 載入的資料,他會自動對接。

原則上到這一步,就可以看到資料囉,此時接的就是多國語系 json 的檔案。


可以做個簡單的切換看看效果:

<nuxt-link :to="switchLocalePath('tw')">TW</nuxt-link>
<nuxt-link :to="switchLocalePath('en')">EN</nuxt-link>

以上,是我目前使用 Nuxt.js 串接多國語系的方法,如果有更好或更簡單的方法,也歡迎分享給我唷,感謝。

歡迎給我點鼓勵,讓我知道你來過 :)

2
Subscribe
Notify of
guest

0 則留言
Inline Feedbacks
View all comments