avatar
set up multiple languages in i18n Vue

• First of all, let us package manager like npm or yarn, install the `vue-i18n` package.

npm install vue-i18n && npm install element-ui

• Once you have installed, in your Vue application, create a lang folder and add language files for each language you want to support. For example, you could create `lang/en.js` file for English and `lang/zh.js` file for Chinese.

- `index.js`

import Vue from 'vue';
import VueI18n from 'vue-i18n';
import Cookies from 'js-cookie';
import elementEnLocale from 'element-ui/lib/locale/lang/en'; 
import elementRuLocale from 'element-ui/lib/locale/lang/ru-RU'; 
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN';
import elementViLocale from 'element-ui/lib/locale/lang/vi';
import enLocale from './en';
import ruLocale from './ru';
import zhLocale from './zh';
import viLocale from './vi';

Vue.use(VueI18n);

const messages = {
  en: {
    ...enLocale,
    ...elementEnLocale,
  },
  ru: {
    ...ruLocale,
    ...elementRuLocale,
  },
  zh: {
    ...zhLocale,
    ...elementZhLocale,
  },
  vi: {
    ...viLocale,
    ...elementViLocale,
  },
};

export function getLanguage() {
  const chooseLanguage = Cookies.get('language');
  if (chooseLanguage) {
    return chooseLanguage;
  }

  const language = (navigator.language || navigator.browserLanguage).toLowerCase();
  const locales = Object.keys(messages);
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale;
    }
  }
  return 'en';
}
const i18n = new VueI18n({
  locale: getLanguage(),
  messages,
});

export default i18n;

- `en.js`

export default {
  route: {
    dashboard: 'Dashboard',
    introduction: 'Introduction',
    ...
};

You can create language files for different languages by cloning the `en.js` file and renaming it to `ru.js`, zh.js, `vi.js` or any other language code that you want to support.

• In summary, we can import the i18n instance into the Vue instance in the app.js file. By doing this, we make the i18n instance available to all components in the Vue application, allowing us to use it for translating text in the components.

import Vue from 'vue';
import Cookies from 'js-cookie';
import ElementUI from 'element-ui';
import App from './views/App';
import i18n from './lang';

import * as filters from './filters';

Vue.use(ElementUI, {
  size: Cookies.get('size') || 'medium',
  i18n: (key, value) => i18n.t(key, value),
});

Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key]);
});

Vue.config.productionTip = false;

new Vue({
  el: '#app',
  router,
  store,
  i18n,
  render: h => h(App),
});

Note: you can use `$t('...')` or `this.$t('...')` in Vue component.

You need to login to do this manipulation!