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')
}
],