公司項目須要國際化,點擊按鈕切換中文/英文vue
npm install vue-i18n --save
import VueI18n from 'vue-i18n' Vue.use(VueI18n) ; const i18n = new VueI18n({ locale: 'zh-CN', // 語言標識, 經過切換locale的值來實現語言切換,this.$i18n.locale messages: { 'zh-CN': require('./common/lang/zh'), // 中文語言包 'en-US': require('./common/lang/en') // 英文語言包 } }) new Vue({ el: '#app', i18n, // 最後 router, template: '<App/>', components: { App } })
zh.js中文語言包: export const lang = { homeOverview:'首頁概覽', firmOverview:'公司概述', firmReports:'財務報表', firmAppendix:'更多附錄', firmIndex:'主要財務指標', firmAnalysis:'對比分析', firmNews:'新聞事件檔案', firmOther:'其餘功能', } en.js 英文語言包: export const lang = { homeOverview:'Home overview', firmOverview:'firmOverview', firmReports:'firmReports', firmAppendix:'firmAppendix', firmIndex:'firmIndex', firmAnalysis:'firmAnalysis', firmNews:'firmNews', firmOther:'firmOther' }
this.$i18n.locale,當你賦值爲‘zh-CN’時,導航欄就變成中文;當賦值爲 ‘en-US’時,就變成英文: <div class="top_btn" @click="changeLangEvent">中文</div> changeLangEvent() { console.log('changeLangEvent'); this.$confirm('肯定切換語言嗎?', '提示', { confirmButtonText: '肯定', cancelButtonText: '取消', type: 'warning' }).then(() => { if ( this.$i18n.locale === 'zh-CN' ) { this.$i18n.locale = 'en-US';//關鍵語句 console.log('en-US') }else { this.$i18n.locale = 'zh-CN';//關鍵語句 console.log('zh-CN') } }).catch(() => { console.log('catch'); this.$message({ type: 'info', }); }); }
靜態渲染:npm
<span v-text="$t('lang .homeOverview')"></span> <span>{{$t('lang .homeOverview')}}</span> 若是是element-ui 的,在要翻譯的前面加上冒號 好比:label="用戶姓名" 就改爲 :label="$t('order.userName')"
動態渲染:element-ui
<span class="el-dropdown-link">{{navCompany}}</span> computed:{ navCompany:function(){ if(this.nav_company){ let str = 'lang'+this.nav_company; return this.$t(str); } } }, <el-submenu v-for="(value, title1, one) in navList" :key="one+1" :index="(one+1).toString()"> <template slot="title"> <router-link :to="linkList[title1]">{{ getTitle(title1) }}</router-link> </template> </el-submenu> methods: { getTitle(title){ let str = 'lang.'+title; return this.$t(str); } }