vue實(shí)現(xiàn)國(guó)際化(vue-i18n)

使用vue-i18n插件來(lái)實(shí)現(xiàn)vue項(xiàng)目中的國(guó)際化功能

vue-i18n安裝

npm install vue-i18n

全局使用

import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

const messages = {
    'en-US': {
        message: {
            hello: 'hello word'
        }
    },
    'zh-CN': {
        message: {
            hello: '歡迎'
        }
    }
}

const i18n = new VueI18n({
    locale:'zh-CN',
    messages
})

// 創(chuàng)建 Vue 根實(shí)例
new Vue({
  i18n,
  ...
}).$mount('#app')

vue頁(yè)面中使用

<p>{{ $t('message.hello') }}</p>

輸出如下

<p>歡迎</p>

可傳參數(shù)

onst messages = {
  en-US: {
    message: {
      hello: '{msg} world'
    }
  }
}

使用模版:

<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>

輸出如下:

<p>hello world</p>

回退本地化

const messages = {
  en: {
    message: 'hello world'
  },
  ja: {
    // 沒(méi)有翻譯的本地化 `hello`
  }
}

上面語(yǔ)言環(huán)境信息的 ja 語(yǔ)言環(huán)境中不存在 message 鍵,當(dāng)我們使用ja環(huán)境中的message時(shí)就會(huì)出現(xiàn)問(wèn)題。

此時(shí),我們可以在 VueI18n 構(gòu)造函數(shù)中指定 fallbackLocale為en,message鍵就會(huì)使用 en 語(yǔ)言環(huán)境進(jìn)行本地化。

如下所示:

const i18n = new VueI18n({
  locale: 'ja',
  fallbackLocale: 'en',
  messages
})

使用如下:

<p>{{ $t('message') }}</p>

輸出如下:

<p>hello world</p>

PS: 默認(rèn)情況下回退到 fallbackLocale 會(huì)產(chǎn)生兩個(gè)控制臺(tái)警告:

[vue-i18n] Value of key 'message' is not a string!
[vue-i18n] Fall back to translate the keypath 'message' with 'en' locale.

為了避免這些警告 (同時(shí)保留那些完全沒(méi)有翻譯給定關(guān)鍵字的警告),需初始化 VueI18n 實(shí)例時(shí)設(shè)置 silentFallbackWarn:true.

如果想要關(guān)閉全部由未翻譯關(guān)鍵字造成的警告,可以設(shè)置silentTranslationWarn: true。
如下:

const i18n = new VueI18n({
  silentTranslationWarn: true,
  locale: 'ja',
  fallbackLocale: 'en',
  messages
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容