vue-i18n 倉庫地址:https://github.com/kazupon/vue-i18nvue
兼容性:git
支持 Vue.js 2.x 以上版本github
安裝方法:(此處只演示 npm)npm
npm install vue-i18n
使用方法:json
一、在 main.js 中引入 vue-i18n (前提是要先引入 vue)瀏覽器
import VueI18n from 'vue-i18n' Vue.use(VueI18n)
二、準備本地的翻譯信息cookie
const messages = { zh: { message: { hello: '好好學習,每天向上!' } }, en: { message: { hello: 'good good study, day day up!' } } }
三、建立帶有選項的 VueI18n 實例app
const i18n = new VueI18n({ locale: 'en', // 語言標識 messages })
四、把 i18n 掛載到 vue 根實例上學習
const app = new Vue({ router, i18n, ...App }).$mount('#app')
五、在 HTML 模板中使用ui
<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
一、新建一個 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 }
二、在 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', }) }) },
效果: