Vue.js引入vue-i18n 實現國際化
- 國際化應該都不陌生,就是一個網站、應用可以實現語言的切換
- 實現:使用vue-i18n 插件
- 安裝依賴:
npm install vue-i18n
- 在 main.js 中引入 vue-i18n
import VueI18n from 'vue-i18n'
//引用vue-i18n
Vue.use(VueI18n)
//使用vue-i18n
var app = new Vue({
el: '#app',
router,
i18n, //將 i18n 掛載到vue實例上
store,
render: h => h(App)
})
const i18n = new VueI18n({
locale: 'zh-CN', // 語言標識
//this.$i18n.locale // 通過切換locale的值來實現語言切換
messages: {
'zh-CN': require('./common/lang/zh'), // 中文語言包
'en-US': require('./common/lang/en') // 英文語言包
}
})
上面的代碼正式將 vue-i18n 引入 vue 項目中,創建一個 i18n 實例對象,方便全局調用。我們通過 this.$i18n.locale
來進行語言的切換,點擊一個按鈕來切換
3. 創建 common 文件夾,寫入對應的en.js 和zh.js
// 使用:vue {{$t('htmlcode.music')}}
// js this.$i18n.t('htmlcode.music')
// 信息提示對應編碼
export const infocode = {
addsuccesscode: '新增成功',
adderrorcode: '新增失敗',
editsuccesscode: '編輯成功',
editerrorcode: '編輯失敗',
deletesuccesscode: '刪除成功',
deleteerrorcode: '刪除失敗',
importsuccesscode: '導入成功',
importerrorcode: '導入失敗',
exportsuccesscode: '導出成功',
exporterrorcode: '導出失敗',
resetcode: '已重置',
searcherrorcode: '搜索失敗',
errorcode: '服務器內部錯誤'
}
// 頁面文字對應編碼
export const htmlcode = {
form: {
empno: '序號',
name: '姓名'
}
}
// 按鈕對應編碼
export const buttoncode = {
handleEditcode: '修改',
handleDeletecode: '刪除',
handleAddcode: '新建',
handleFiltercode: '查詢',
resetTempcode: '重置',
importFromcode: '導入',
exportFromcode: '導出'
}
4. 使用:
最後我們只需要通過觸發事件的形式,來控制 locale 的值,去調用對應的語言包就可以實現國際化啦。
點擊事件進行切換
data:{
lang :"zh-CN"
}
/**
* 切換語言
*/
changeLangEvent() {
this.$confirm('確定切換語言嗎?', '提示', {
confirmButtonText: '確定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
if ( this.lang === 'zh-CN' ) {
this.lang = 'en-US';
this.$i18n.locale = this.lang;//關鍵語句
}else {
this.lang = 'zh-CN';
this.$i18n.locale = this.lang;//關鍵語句
}
}).catch(() => {
this.$message({
type: 'info',
});
});
}
點出的‘’關鍵語句‘’:this.$i18n.locale,當你賦值爲‘zh-CN’時,導航欄就變成中文;當賦值爲 ‘en-US’時,就變成英文
- vue-i18n 數據渲染的模板語法
v-text:
<span v-text="$t('m.music')"></span>
{{}}:
<span>{{$t('m.music')}}</span>
注意:在js中使用
<span>{{$t('version.email')}}</span>
<el-form-item :label="$t('table.license_no')" prop="license">
<el-input v-model="dataform.license" :disabled="disabled" :placeholder="$t('table.license_no')"></el-input>
</el-form-item>
tableColumns: [
{
label: this.$i18n.t('htmlcode.form.empno')
},
{
label: this.$i18n.t('htmlcode.form.empno')
}
],