preface

Vue + VUe-I18N implements multiple languagesCopy the code

Main Contents of this paper

  • The installation
  • Multilingual configuration
  • Element has built-in language internationalization
  • The pit and the solution

The installation

npm install vue-i18n
Copy the code

configuration

  • i18n.js

import Vue from 'vue';
import locale from 'element-ui/lib/locale';
import VueI18n from 'vue-i18n';

import en from './langs/en';
import sc from './langs/cn';
import tc from './langs/tc';

Vue.use(VueI18n);
const i18n = new VueI18n({
  //locale: localStorage.lang || 'en',
  locale: localStorage.getItem('localize_lang') | |'en'Messages: {sc, // Chinese en, // English tc // traditional}}); locale.i18n((key, value) => i18n.t(key, value)); // Important: in order to achieve the element plug-in multilanguage switchexport default i18n;
Copy the code
  • Main.js (referencing i18n)
import Vue from 'vue';
import i18n from './i18n/i18n';

new Vue({
  el: '#app',
  i18n
});
Copy the code
  • Langs creates a new folder for language files
  • Add as many languages as you can
// en.js
const en ={
   name:'fannie'         
}
export default  en 
// cn.js
  import zhLocale from 'element-ui/lib/locale/lang/zh-CN';
const cn ={
   name:'Fanny', & emsp;   . zhLocale }export default  cn 
Copy the code
  • Demo.vue (Applications within components)
<template>
<div>{{$t('name')}}</div>
<el-select v-model="langType" class="changeLangType" size="mini" @change="changeLangType">
          <el-option value="en" label="English"></el-option>
          <el-option value="cn" label="Simplified Chinese"></el-option>
          <el-option value="tc" label="Traditional Chinese"></el-option>
    </el-select> 
</template>
<script>
export default {
  data() {return{ &emsp; &emsp; langType:' '}; }, methods:{ changeLangType(type) {localStorage.setItem('locale'.type);
 this.$i18n.locale = type; }}}; </script>Copy the code

ElementUI has built-in internationalization

  • Open the Element website, which contains the international documentation. You can see how many languages are now supported on the website
Import zhLocale from in cn.js'element-ui/lib/locale/lang/zh-CN'; . zhLocaleCopy the code

The pit and the solution

1.Value of key ‘xxx’ is not string! Cannot translate the value of keypath ‘xxx’. Use the value of keypath as default.

Solution:

  • Maybe your character is not declared, can not find.
  • Reference configuration Check these areas carefully, such as reference paths
  • For example, in mian. Js is imported
  • Make sure you write messages

Fannie summary

Be careful and follow the stepsCopy the code