在基于vue-cli项目开发过程中,多语言切换功能可使用vue-i18插件,具体实现方法如下:

step1: 在项目中安装vue-i18插件

cnpm install vue-i18n --save-dev

step2:在项目的入口文件main.js中引入vue-i18n插件

import Vue from 'vue'
import router from './router'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
  locale: 'zh', // 语言标识
  messages: {
    'zh': require('./assets/lang/zh'),
    'en': require('./assets/lang/en')
  }
})
// vue实例中引入
/* eslint-disable no-new */
new Vue({
  el: '#app',
  i18n,
  router,
  template: '<Layout/>',
  components: {
    Layout
  },
})

step3:页面中使用

在模板中使用时,大概有以下3种情况,若有疏漏,望大家指正

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)待补充...

step4:页面上进行中英文切换,在中英文切换的按钮上绑定事件,如下:

tabEn: function () {
  this.$i18n.locale = 'en'
},
tabCn: function () {
  this.$i18n.locale = 'zh'
}
至此,vue-i18n插件使用完结。


Logo

前往低代码交流专区

更多推荐