使用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
})