一、安装
安装命令:
npm install vue-i18n
如果在一个系统中使用它,你必须通过Vue.use() 明确地安装 vue-i18n
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
二、使用
在src下创建lang文件夹(文件语言包)
1.准备语言包,本例中准备两个分别是中文和英文:zn、en。在 lang 下创建两个文件,zn.js 和 en.js。
// zn.js
export default {
main:{
message:"信息",
display:"显示"
}
};
// en.js
export default {
main:{
message:"message",
display:"display"
}
}
三、实现语言翻译
在 main.js 中将 i18n 注入 vue 中
import i18n from './lang'
new Vue({
el: '#app',
router,
store,
i18n, // 注入,不能缺少
components: { App },
template: '<App/>'
})
代码示例:
<template>
<div style="width: 100%;">
<div>
<span>{{$t('main.message')}}</span>
<button @click="changeLang">切换语言</button>
</div>
</div>
</template>
<!--这种写法也行
<el-form-item label-width="400" :label="$t('apply.feeFrom')" prop="feeFrom">
-->
<script>
export default {
methods: {
changeLang() {
if(this.$i18n.locale === 'zn'){ // 判断当前语言
this.$i18n.locale = 'en' // 设置当前语言
} else {
this.$i18n.locale = 'zn'
}
}
}
}
</script>