主要由如下幾個模塊組成由 :vue
nuxt.config.js
locales/index.js
locales/zh_CN.json
utils/config.js
nuxt.config.js
module.exports = { // other code ... plugins: [ { src: '~/locales/index.js' } // locales 目錄沒有放置在 plugins 目錄下主要是爲了引用 json 文件方便 ], // other code ... }
locales/index.js
從 Nuxt.js 應用國際化(i18n)的示例 變化而來 :
import Cookies from 'js-cookie' import VueI18n from 'vue-i18n' import Vue from 'vue' Vue.use(VueI18n) export default ({ app, store }) => { const data = {} const locale = Cookies.get('hb_lang') || 'en_US' const readDir = ['en_US', 'zh_CN', 'th_TH'] for (let i = 0; i < readDir.length; i++) { data[readDir[i]] = Object.assign({}, require(`./${readDir[i]}.json`)) } // Set i18n instance on app // This way we can use it in middleware and pages asyncData/fetch app.i18n = new VueI18n({ locale, fallbackLocale: locale, // 語言環境中不存在相應massage鍵時回退到指定語言 messages: data }) }
locales/zh_CN.json
{ "solutions":"解決方案", "global":{ "login":"登陸", "register":"註冊", "logout":"註銷", "join":"加入", "confirm":"確認", "submit":"提交", "reset":"重置", "all":"所有", "open":"打開", "close":"關閉", "userList": "用戶列表" }, "headerNav": { "home": "首頁", "users":"用戶" }, "login": { "username": "用戶名", "password": "密碼" }, "footer": { "TermsOfUse": "使用條款", "PrivacyPolicy": "隱私保護" } }
調用方法 : <h1 class="solutions">{{ $t('solutions') }}</h1>
json
utils/config.js
import Cookies from 'js-cookie' const LangKey = 'hb_lang' // 語言 export function getLanguage() { return Cookies.get(LangKey) } export function setLanguage(data) { return Cookies.set(LangKey, data) } export function removeLanguage() { return Cookies.remove(LangKey) }
其中 , 當須要動態切換語言時,調用 setLanguage 方法便可, 例如:segmentfault
import { setLanguage } from '~/utils/config.js' setLanguage('en_US')
以上配置須臾結合 Vue
的 {{}}
進行編輯, 例如上文所提到的 : <h1 class="solutions">{{ $t('solutions') }}</h1>
cookie
假若像下面這樣則會致使切換語言時, 沒法動態即時更新文案 :app
// 不要這樣寫, 解決方法在下面 <template> <div> <div class="solutions">{{ solutions }}</div> </div> </template> <script> export default { data() { return { solutions : this.$t('solutions') } } } </script>
解決方法 :async
<template> <div> <div class="solutions">{{ solutions }}</div> </div> </template> <script> export default { watch: { '$store.state.lang'(language) { this.init() } }, data() { return { solutions : this.$t('solutions') } }, created() { this.init() }, methods: { init(){ this.solutions = this.$t('solutions') } }, } </script>