vue-i18n 倉庫地址:https://github.com/kazupon/vue-i18n
兼容性:
支持 Vue.js 2.x 以上版本
安裝方法:(此處只演示 npm)
npm install vue-i18n
使用方法:
1、在 main.js 中引入 vue-i18n (前提是要先引入 vue)
import VueI18n from 'vue-i18n' Vue.use(VueI18n)
2、准備本地的翻譯信息
const messages = {
zh: {
message: {
hello: '好好學習,天天向上!'
}
},
en: {
message: {
hello: 'good good study, day day up!'
}
}
}
3、創建帶有選項的 VueI18n 實例
const i18n = new VueI18n({
locale: 'en', // 語言標識
messages
})
4、把 i18n 掛載到 vue 根實例上
const app = new Vue({
router,
i18n,
...App
}).$mount('#app')
5、在 HTML 模板中使用
<div id="app">
<h1 style="font-size: 16px; text-align: center;">{{ $t("message.hello") }}</h1>
</div>
查看運行效果:

我們剛才選定的語言標識是 “en” 英語,現在改成 “zh” 中文,並查看效果
const i18n = new VueI18n({
locale: 'zh', // 語言標識
messages
})

這樣就可以輕松實現國際化了,實際開發中,頁面內容肯定是很多的,我們可以把對應語言的信息保存為不同的 json對象
const i18n = new VueI18n({
locale: 'en', // 語言標識
messages: {
'zh': require('./common/lang/zh'),
'en': require('./common/lang/en')
}
})
zh.js
// 注意:一定是 exports,不是 export,否則會報錯,報錯信息是下列的中的內容不是 string
module.exports = {
message: {
title: '運動品牌'
},
placeholder: {
enter: '請輸入您喜歡的品牌'
},
brands: {
nike: '耐克',
adi: '阿迪達斯',
nb: '新百倫',
ln: '李寧'
}
}
en.js
module.exports = {
message: {
title: 'Sport Brands'
},
placeholder: {
enter: 'Please type in your favorite brand'
},
brands: {
nike: 'Nike',
adi: 'Adidas',
nb: 'New Banlance',
ln: 'LI Ning'
}
}
接下來,在HTML 模板中使用,要特別注意在 js 中的國際化寫法
// HTML
<div id="app">
<div style="margin: 20px;">
<h1>{{$t("message.title")}}</h1>
<input style="width: 300px;" class="form-control" :placeholder="$t('placeholder.enter')">
<ul>
<li v-for="brand in brands">{{brand}}</li>
</ul>
</div>
</div>
// JS
data () {
return {
brands: [this.$t('brands.nike'), this.$t('brands.adi'), this.$t('brands.nb'), this.$t('brands.ln')]
}
},
查看編譯效果:

現在換成英文的:

在上面的操作中,我們都是通過手動修改 locale 的屬性值來切換語言,實際上,更希望瀏覽器自動識別,這里可以借助於 cookie
1、新建一個 cookie.js 文件,用於讀取cookie
function getCookie(name,defaultValue) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
if (arr = document.cookie.match(reg))
return unescape(arr[2]);
else
return defaultValue;
}
export {
getCookie
}
2、在 main.js 中引入這個js,並通過 PLAY_LANG 屬性來獲取瀏覽器的語言
const i18n = new VueI18n({
locale: getCookie('PLAY_LANG','zh'), // 語言標識
messages: {
'zh': require('./common/lang/zh'),
'en': require('./common/lang/en')
}
})
這里需要注意兩個極易出錯的地方:
(1)、將 $t() 寫成了 $()

(2)、json 中在同一個對象里有同名屬性

vue-i18n 提供了一個全局配置參數叫 “locale”,通過改變 locale 的值可以實現不同語種的切換

下面的案例借用了 Element UI 的彈窗樣式,上面的步驟不再贅述,直接上核心代碼
// template
<h2>{{$t('test')}}</h2>
<button type="button" class="btn btn-success" @click="changeLocale">中文/EN</button>
// js方法
changeLocale () {
this.$confirm(this.$t('layer.toggle'), this.$t('layer.tips'), {
confirmButtonText: this.$t('button.ok'),
cancelButtonText: this.$t('button.cancel'),
type: 'warning'
}).then(() => {
let locale = this.$i18n.locale
locale === 'zh' ? this.$i18n.locale = 'en' : this.$i18n.locale = 'zh'
}).catch(() => {
this.$message({
type: 'info',
})
})
},
效果:

在配合 Element-UI 一起使用時,會有2個問題:
(1)、頁面刷新后,通過按鈕切換的語言還原成了最初的語言,無法保存
(2)、框架內部自帶的提示文字無法更改,比如像時間選擇框內部中的提示文字
關於第一個問題,可以在初始化VueI18n實例時,通過 localStorage 來為 locale 對象賦值
const i18n = new VueI18n({
locale: localStorage.getItem('locale') || 'zh',
messages
})
在切換語言的時候可以緩存不同的語言選項,並且可以長期保存,不會因為刷新網頁而改變locale 的屬性值
<div class="lang">
<el-dropdown>
<i class="iconfont icon-language4"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item @click.native="toggleLang('zh')" :disabled="$i18n.locale == 'zh'">中文</el-dropdown-item>
<el-dropdown-item @click.native="toggleLang('en')" :disabled="$i18n.locale == 'en'">English</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
toggleLang(lang) {
if(lang == 'zh'){
localStorage.setItem('locale', 'zh')
this.$i18n.locale = localStorage.getItem('locale')
this.$message({
message: '切換為中文!',
type: 'success'
})
} else if (lang == 'en') {
localStorage.setItem('locale', 'en')
this.$i18n.locale = localStorage.getItem('locale')
this.$message({
message: 'Switch to English!',
type: 'success'
})
}
關於第二個問題,更改Element 組件內部語言,這里還涉及到 手動處理 vue-i18n@6.x 兼容性問題。官網已經做了詳細介紹,這里依葫蘆畫瓢跟着實現一下

i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locale from 'element-ui/lib/locale';
import zh from './langs/zh'
import en from './langs/en'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(VueI18n)
const messages = {
en: Object.assign(en, enLocale),
zh: Object.assign(zh, zhLocale)
}
console.log(messages.zh)
const i18n = new VueI18n({
locale: localStorage.getItem('locale') || 'zh',
messages
})
locale.i18n((key, value) => i18n.t(key, value)) //為了實現element插件的多語言切換
export default i18n
按照如上把國際化文件都整合到一起,避免main.js 中大段引入相關代碼。main.js 中與 i18n 相關的就只剩兩行代碼
import i18n from './i18n/i18n' // 1行
window.app = new Vue({
el: '#app',
router,
store,
i18n, // 2行
components: { App },
template: '<App/>'
})
效果如下:

以上demo地址:https://github.com/frwupeng517/element-admin/tree/master/src/i18n
簡單配置 參考: https://www.jianshu.com/p/2d3119f9bfd8

