Use vue-i18n in vue project to realize multi-language switching function
In the project, it is necessary to realize the multi-language switching function. There are many ways to realize it. The following will introduce the use of vue-i18n to realize it.
Vue I18n Reference Documentation
1. Install the vue-i18n dependency package
npm install --save vue-i18n
2. Configure zh-CN and en-US files
Configure the Chinese and English files that need to be switched between zh-CN.json and en-US.json in api/languages
// zh-CN.json
{
"langName": "中文",
"menuList": {
"home": "主页",
"user": "用户管理",
"roles": "角色管理",
"notice": "通知公告",
"logs": "日志管理"
}
}
// en-US.json
{
"langName": "en-US",
"menuList": {
"home": "Home",
"user": "User management",
"roles": "Role management",
"notice": "Notice Announcement",
"logs": "log management"
}
}
3. Globally mount the i18n plugin in main.js
Do a global import in main.js, note: import the correct resource file
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh-CN', // 将要切换的语言,可以通过url拼的参数获取,用户行为select选择获取,本地manifest配置获取等,根据场景动态获取
messages: {
'zh-CN': require('./api/languages/zh-CN.json'), // 本地资源文件,我这里配2个语言,中文&英文,src下根据个人情况放置
'en-US': require('./api/languages/en-US.json')
}
});
const vm = new Vue({
el: '#app',
i18n,
store,
router,
render: c => c(App),
});
4. Use in the page
// template中直接使用
<template>
<div class="menuWrap">
<div class="menuInner">
{
{
$t('menuList.home') }}
</div>
<div class="menuInner">
{
{
$t('menuList.user') }}
</div>
<div class="menuInner">
{
{
$t('menuList.roles') }}
</div>
</div>
</template>
// script中直接使用
<script>
export default {
data () {
return {
langName: '',
}
},
created () {
this.langName = this.$t('langName')
}
}
</script>
5. Language switching
<template>
<div class="langWrap">
<div class="langInner" @click="handleCh">
中文
</div>
<div class="langInner" @click="handleEn">
英文
</div>
</div>
</template>
<script>
export default {
data () {
return {
langName: '',
}
},
methods: {
handleCh() {
this.$i18n.locale = 'zh-CN'
},
handleEn() {
this.$i18n.locale = 'en-US'
},
}
}
</script>
Finally: If the installation of vue-i18n on npm is successful, but sometimes there is an error of Cannot read properties of undefined (reading 'install') when quoting , you can refer to my other article: Solving the problem of using vue-i18n in vue projects i18n reports the problem of Cannot read properties of undefined (reading 'install')