• First, install vuE-I18N

Kazupon.github. IO /vue-i18n/zh…

  • Import and register in main.js
import i18n from './lang';
// Set internationalization
Vue.use(ElementUI, {
  i18n: (key, value) = > i18n.t(key, value)
});

new Vue({
  el: '#app',
  i18n,
  render: h= > h(App)
});
Copy the code
  • SRC directory to create language package folder lang/index.js
/ / index. Js file
import Vue from 'vue';
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 messages = {
  en: {
    message: {
      hello: '{msg} world'
    },
    ...enLocale
  },
  zh: {
    message: {
      hello: '{MSG} the world'
    },
    ...zhLocale
  }
};
const i18n = new VueI18n({
  locale: 'zh'.// set locale
  messages // set locale messages
});

export default i18n;
Copy the code
  • Effect preliminary search, randomly find a page to try, this page will show hello world
<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>
<p v-html="$t('message.hello')" />
Copy the code

Look, is not very simple, has already had the rudiment, began finishing

  • In general, there is a lot of text to translate, so it is best to have separate file management for each language. Create new files lang/en.js and lang/en.js and write some test data
//zh.js
export default {
  app: {
    LanguageChage: 'Language switch'.editPassword: 'Change password'.signOut: 'log out'}};Copy the code
//en.js
export default {
  app: {
    LanguageChage: 'Language switching'.editPassword: 'Change Password'.signOut: 'Sign out'}};Copy the code
  • The next step is to encapsulate a component that switches languages and saves the language state to cookies and Vuex.

Before encapsulating the component, let’s encapsulate a method, save the language state value, update the previous lang/index.js file, mainly the getLanguage method

import Vue from 'vue';
import VueI18n from 'vue-i18n';
import Cookies from 'js-cookie';
import enLocaleElement from 'element-ui/lib/locale/lang/en';
import zhLocaleElement from 'element-ui/lib/locale/lang/zh-CN';
import zhLocale from './zh';
import enLocale from './en';

Vue.use(VueI18n);

// Locale information
const messages = {
  en: {... enLocale, ... enLocaleElement },zh: {... zhLocale, ... zhLocaleElement } };// Get the locale and preserve the state
export function getLanguage() {
  const cookieLanguage = Cookies.get('language');
  if (cookieLanguage) return cookieLanguage;

  const browerLanguage = (navigator.language || navigator.browserLanguage).toLowerCase();
  const locales = Object.keys(messages);

  for (const locale of locales) {
    if (browerLanguage.indexOf(locale) > - 1) {
      returnlocale; }}}const i18n = new VueI18n({
  locale: getLanguage(),
  messages,
  fallbackLocale: 'zh'
});

/ / hot update
if (module.hot) {
  module.hot.accept(['./en'.'./zh'].function() {
    i18n.setLocaleMessage('en'.require('./en').default);
    i18n.setLocaleMessage('zh'.require('./zh').default);
  });
}

export default i18n;
Copy the code

The language field is added in vuex warehouse. Generally, we should use Vuex. Here, I use vuex module mode to write.

// app.js this is my store file

import { getLanguage } from '@/lang/'; // Introduce the previously written method
// Add the language field to state
const state = {
  language: getLanguage()
};

const mutations = {
  SETLANGE: (state, language) = > {
    state.language = language;
    Cookies.set('language', language); }};const actions = {
  setLanguage({ commit }, language) {
    commit('SETLANGE', language); }};export default {
  namespaced: true,
  state,
  mutations,
  actions
};

Copy the code
  • OK, now that the preparation is complete, encapsulate the language switching components and create a new launageselect.vue file
<template> <el-dropdown trigger="click" class="international" @command="handleSetLanguage"> <el-dropdown-menu slot="dropdown"> <el-dropdown-item :disabled="language==='zh'" command="zh"> 中文 </el-dropdown-item> <el-dropdown-item :disabled="language==='en'" command="en"> English </el-dropdown-item> </el-dropdown-menu> </el-dropdown> </template> <script> export default { computed: { language() { return this.$store.getters.language; }}, methods: {handleSetLanguage(lang) {// Set the current locale through the root instance of VueI18n http://kazupon.github.io/vue-i18n/zh/api/#%E9%9D%99%E6%80%81%E5%B1%9E%E6%80%A7 this.$i18n.locale = lang; this.$store.dispatch('app/setLanguage', lang); this.$message({ message: 'Switch Language Success', type: 'success' }); }}}; </script>Copy the code

  • At this point, the basic internationalization framework is complete and ready to go.

  • Wait, that’s not all. This is what matters.

The menu of a VUE project is usually written in route, so there is no way to use template syntax for internationalization directly, so we need to encapsulate a method to handle menu titles

/** * generate character - internationalization using * @param {*} lanuageKey language object key * @param {*} title the value to be converted */
export function generateText(lanuageKey, title) {
  const key = this.$te(`${lanuageKey}.${title}`);
  if (key) {
    return this.$t(`${lanuageKey}.${title}`);
  }
  return title;
}

Copy the code

Find the file rendering the menu and introduce the method just described to format the menu title

  <app-link v-if="onlyOneChild.meta" :to="resolvePath(onlyOneChild.path)"> <el-menu-item :index="resolvePath(onlyOneChild.path)" :class="{'submenu-title-noDropdown':! isNest}" > <item :icon="onlyOneChild.meta.icon||(item.meta&&item.meta.icon)" :title="generateText('route', Onlyonechild.meta. Title)" /> </el-menu-item> </app-link> // import {generateText} from '@/utils/'; GenerateText {generateText}Copy the code

Your configuration should look like this

// zh.js
export default {
  route: {
    home: 'home',}}//router.js (the home in the title should correspond to the key in your en.js)
  {
    path: '/'.component: Layout,
    redirect: '/home'.children: [{
      path: 'home'.name: 'Home'.component: (a)= > import('@/views/home/index'),
      meta: { title: 'home'.icon: 'home'}}}]Copy the code

Your menu items will now render normally

  • To this formal end, in fact, quite simple, of course, i18N has a lot of syntax, we consult the document, thank you!