github地址:https://github.com/kazupon/vue-i18n/tree/5.x
说明文档:http://kazupon.github.io/vue-i18n/guide/started.html#html
效果图:
英文.png
中文.png
引入vue-i18n
npm install vue-i18n --save
在main.js同级目录创建一个lang文件夹放置文件(一般是在assets文件夹里创建,随你喜欢)
目录.png
对i18n.js文件进行配置
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n);
// 以下为语言包单独设置的场景,单独设置时语言包需单独引入
const messages = {
'zh_CN': require('./zh'), // 中文语言包
'en_US': require('./en') // 英文语言包
}
// 最后 export default,这一步肯定要写的。
const i18n = new VueI18n({
locale : localStorage.getItem('locale') || 'zh_CN', // set locale 默认显示中文
messages : messages // set locale messages
})
export default i18n;
zh.js文件
module.exports = {
payError:{
'title':'支付失败',
'text':'啊哦,支付失败了,换台设备试一下吧',
'replace':'换台设备扫一扫',
},
}
en.js文件
module.exports = {
payError:{
'title':'Payment Failure',
'text':"Ah, the payment failed. Let's try another device",
'replace':'Change the device scan',
},
}
使用的页面,使用的是{{}}
,里面的$t
是固定模版,不要写错哦,否则会做字符串处理渲染
{{$t("payError.title")}}
{{$t("payError.text")}}
在main.js中引入配置的i18n.js文件
import i18n from"./lang/i18n.js"
const app = new Vue({
el: "#app",
i18n, //挂在i18n,可以全局使用
router,
store,
render: function(h) {
return h(App);
}
});
中英文切换方法
中 /
EN
export default {
data(){
return{
isChinese:true,//默认显示中文
}
},
created() {
if(localStorage.getItem('locale') == 'zh_CN'){
this.isChinese = true;
}else{
if(this.$i18n.locale == 'zh_CN'){
this.isChinese = true;
}else{
this.isChinese = false;
}
}
},
methods: {
handleLanguage(){
this.isChinese = !this.isChinese;
if(this.$i18n.locale == 'zh_CN'){
this.$i18n.locale = 'en_US'; //设置的值必须跟i18n.js里messages对应的值一样,否则会报undefined
localStorage.setItem('locale','en_US')
localStorage.setItem('isChinese',false)
}else{
this.$i18n.locale = 'zh_CN';
localStorage.setItem('locale','zh_CN')
localStorage.setItem('isChinese',true)
}
},
}
}
这里有一点要注意,localStorage存储的值会自动转为字符串,所以在用的时候不能直接判断true/false,必须转类型或者根据字符串判断。