vue的element-ui 中 i18N国际化

i18N

1.在main.js中引入i8n .

import VueI18n from 'vue-i18n'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'

Vue.use(VueI18n)

// 语言切换
const i18n = new VueI18n({
     
  locale:localStorage.getItem('niulanguage')|| 'zh',
  messages:{
     
    'zh':Object.assign(require('./lang/zh.js'),zhLocale),
    'en':Object.assign(require('./lang/en.js'),enLocale),//将我们项目中的语言包与Element的语言包进行合并
    },
});
Vue.use(ElementUI,{
     
  i18n:(key,value) =>i18n.t(key,value) //重点!!在注册Element时设置i18n的处理方法(这里有个小坑)
});


var vv = new Vue({
     
  i18n
})
//vv.$t('l.qdl')



new Vue({
     
  el: '#app',
  i18n,//使用
  components:{
     
    App
  }
})

2.header头部切换中英文

 <el-dropdown>
      <span class="el-dropdown-link" style="color:#fff">
          {
     {
     lang1}}
          <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="toggleLang('zh')"  :disabled="$i18n.locale == 'zh'">中文</el-dropdown-item>
          <el-dropdown-item @click.native="toggleLang('en')" :disabled="$i18n.locale == 'en'">English</el-dropdown-item>
      </el-dropdown-menu>
 </el-dropdown>

 data() {
     
    return {
     
      lang1:"中文"
    };
  },
 mounted() {
     
    if(localStorage.getItem("niulanguage")=='en'){
     
      this.lang1="English"
    }else {
     
      this.lang1="中文";
    }
}
 methods: {
     
    toggleLang(lang) {
     
      if (lang == "zh") {
     
        this.lang1="中文";
        localStorage.setItem("niulanguage", "zh");
        this.$i18n.locale = localStorage.getItem("niulanguage");
        this.$message({
     
          message: "切换为中文!",
          type: "success",
        });
         this.$router.go(0);
      } else if (lang == "en") {
     
        this.lang1="English";
        localStorage.setItem("niulanguage", "en");
        this.$i18n.locale = localStorage.getItem("niulanguage");
        this.$message({
     
          message: "Switch to English!",
          type: "success",
        });
        this.$router.go(0);//切换完刷新页面
      }
    },
 }
  1. 创建一个 zh.js
  2. 创建一个 en.js

你可能感兴趣的:(vue.js)