第一步
npm install vue-i18n --save-dev
第二步
在项目的入口文件main.js中引入vue-i18n插件
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh', // 语言标识
messages: {
'zh': require('./assets/lang/zh'), 例如:zh.js的路径
'en': require('./assets/lang/en') 例如:en.js的路径
}
})
new Vue({
el: '#app',
i18n,
router,
})
第三步
/**zh.js文件**/
module.exports = {
menu : {
home:"首页"
},
content:{
main:"这里是内容"
}
}
/**en.js文件**/
module.exports = {
menu : {
home:"home"
},
content:{
main:"this is content"
}
}
语法注意:
1)在标签内作为正文内容
<div class="title">{{$t('menu.home')}}</div>
2)作为标签属性使用
<input :placeholder="$t('content.main')" type="text">
3)作为js中文字使用时
console.log(this.$t('content.main'));
4)`${this.$t('content.main')}`
第四步
页面上进行中英文切换,在中英文切换的按钮上绑定事件,如下
tabEn: function () {
this.$i18n.locale = 'en'
},
tabCn: function () {
this.$i18n.locale = 'zh'
}