Vue – i18n

Localize

Localize is one of important topic to expand application.
There are some library to support it for vue.
I want to introduce one of them.

vue-i18n made by kazupon is good library for i18n

vue-i18n

To install this, it’s easy.

npm intall --save vue-i18n

Same as other library, creating i18n object and pass it to Vue arguments.
I use previous entry example(made using vue-cli) and clean codes

If you don’t know it, please check my previous vuex entry (Vue – vuex)

This is project structure

vuex2
|- src
    |- assets
    |- components
    |      |- FieldInput.vue    
    |      |- MsgDiv.vue
    |      |- Page.vue         Support i18n
    |- i18n
    |      |- index.js         setup i18n
    |      |- message.json     localization file
    |- router
    |      |- index.js
    |- store
    |      |- index.js
    |- App.vue
    |- main.js         Add parameter for i18n

Let’s check core part first

i18n/index.js

import Vue from 'vue';
import VueI18n from 'vue-i18n';

const data = require('./message.json');


Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: navigator.language.split("-")[0],   // Use browser first language
  messages: data
});

export default i18n

I use browser first language.
If you want to set specific language, you can change like this

const i18n = new VueI18n({
  locale: 'ja'
  messages: data
});

i18n/message.json

{
  "ja": {
    "message": "チワッス"
  },
  "en": {
    "message": "Hi"
  }
}

Add json style data.
I supported both Japanese and English. We can write 2 languages in the same file.

main.js

Set i18n library to Vue object

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import i18n from './i18n'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  i18n,
  router,
  template: '<App/>',
  components: { App },
  store
})

components/Page.vue

Localize UI

<template>
  <div>
    <FieldInput></FieldInput>
    <button v-on:click="clickAction">{{ $t("message") }}</button>
    <MsgDiv></MsgDiv>
  </div>
</template>

<script>
import FieldInput from '@/components/FieldInput'
import MsgDiv from '@/components/MsgDiv'
import { mapActions } from 'vuex'

export default {
  name: 'Page',
  date() {
    return {
      message : ''
    }
  },
  methods: {
    ...mapActions('Page', {
      'clickAction': 'clickAction'
    })
  },
  components: {
    FieldInput,
    MsgDiv
  }
}
</script>

<style>
</style>

The point is {{$t(“key”)}}
This part will be localized

Ref

kazupon/vue-i18n
Vue.jsで始める多言語対応