1.安装
npm install vue-i18n
在main.js中引用下面代码
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
2.在src下新建lang文件夹 存放3个文件 zn.js en.js index.js
// -------- zn.js ---------
export default {
main:{
message:"消息",
display:"展示"
}
};
// --------- en.js----------
export default {
main:{
message:"message",
display:"display"
}
}
// ------------index.js----------
import Vue from "vue";
import VueI18n from 'vue-i18n'
import zn from "./zn"
import en from "./en"
Vue.use(VueI18n); // 全局注册国际化包
// 准备翻译的语言环境信息
const i18n = new VueI18n({
locale: "zn", // 初始化中文
messages: {
"zn":zn,
"en":en
}
});
export default i18n
3.使用方法
直接使用
<template>
<div style="width: 100%;">
<div>
<div>
<span>{{$t('main.message')}}</span>
</div>
</div>
</div>
</template>
语言切换
<template>
<div style="width: 100%;">
<div>
<div>
<span>{{$t('main.message')}}</span>
<button @click="changeLang">切换语言</button>
</div>
</div>
</div>
</template>
<script>
export default {
methods: {
changeLang() {
if(this.$i18n.locale === 'zn'){ // 判断当前语言
this.$i18n.locale = 'en' // 设置当前语言
} else {
this.$i18n.locale = 'zn'
}
}
}
}
</script>
data变量翻译
//假如页面某个名称绑定了 data 中变量,即可能存在多个值,此时又该如何进行语言翻译?
//如下,“msg”存在多个取值,我们希望在切换“msg”值同时根据当前语言环境进行翻译。
<template>
<div style="width: 100%;">
<div>
<div>
<span>{{$t('main.message')}}</span>
<button @click="changeLang">切换语言</button>
</div>
<p>{{msg}}</p>
<button @click="changeWord">切换msg值</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
msg:'message'
}
},
methods: {
changeLang() {
if(this.$i18n.locale === 'zn'){ // 判断当前语言
this.$i18n.locale = 'en' // 设置当前语言
} else {
this.$i18n.locale = 'zn'
}
},
changeWord() {
if(this.msg === 'message'){
this.msg = 'display'
} else {
this.msg = 'message'
}
},
}
}
</script>
问题报错
如果控制台出现这种问题
报错的原因主要是因为当前使用的版本不匹配,解决方案入下。(复制终安装无脑即可)
npm install vue-i18n@8
详细介绍请查看官方文档
i18n官网