使用vue-i18n插件來實現vue項目中的國際化功能
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
})
// 創建 Vue 根實例
new Vue({
i18n,
...
}).$mount('#app')
vue頁面中使用
<p>{{ $t('message.hello') }}</p>
輸出如下
<p>歡迎</p>
可傳參數
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: {
// 沒有翻譯的本地化 `hello`
}
}
上面語言環境信息的 ja 語言環境中不存在 message 鍵,當我們使用ja環境中的message時就會出現問題。
此時,我們可以在 VueI18n 構造函數中指定 fallbackLocale為en,message鍵就會使用 en 語言環境進行本地化。
如下所示:
const i18n = new VueI18n({
locale: 'ja',
fallbackLocale: 'en',
messages
})
使用如下:
<p>{{ $t('message') }}</p>
輸出如下:
<p>hello world</p>
PS: 默認情況下回退到 fallbackLocale 會產生兩個控制台警告:
[vue-i18n] Value of key 'message' is not a string!
[vue-i18n] Fall back to translate the keypath 'message' with 'en' locale.
為了避免這些警告 (同時保留那些完全沒有翻譯給定關鍵字的警告),需初始化 VueI18n 實例時設置 silentFallbackWarn:true
.
如果想要關閉全部由未翻譯關鍵字造成的警告,可以設置silentTranslationWarn: true
。
如下:
const i18n = new VueI18n({
silentTranslationWarn: true,
locale: 'ja',
fallbackLocale: 'en',
messages
})