Vue のi18nを✅

「3時間」MVP完成までの残された可処分時間。Herokuデプロイエラーに苦しめられているので、寝ている間に脳内で勝手にデバックしてくれないかなと期待しているスバルです。

さて、今回はVueのi18n化に関して学習していきたいと思います。

 

i18nとは

i18n とは、internationalization(国際化)の略。 ⇒ i (nternationalizatio = 18文字) n だから

どう使うのか

まず、vue-i18nをインストールします

yarn add vue-i18n
or
npm install vue-i18n

次に、ファイルに書き出していきます。

登場人物は4人です。

  • assets/model/analyze.rb
  • frontend/packs/hello_vue.js(main.js)
  • frontend/components/locales/ja.json
  • frontend/pages/Result.vue(vueファイルならなんでもいい)

enumで設定した値を日本語で表示させたい.

Image from Gyazo

analyze.rb

診断内容を保存するテーブルです。

class Analyze < ApplicationRecord
  belongs_to :user
  enum next_nomivation_types: { flesh: 0, tipsy: 1, heavy_drunk: 2 } #1
  enum sake_strongness_types: { weak: 0, normal: 1, strong: 2 } #2
end

それぞれ、

  1. 次の飲み会に向けた気分
  2. お酒の強さ

を表しています。

hello_vue.js

外部ライブラリを読み込ませてVueインスタンスを作るmain.jsです。

import Vue from 'vue';
import App from '../App';
import vuetify from '../plugins/vuetify';
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'ja',
  fallbackLocale: 'ja',
  messages: {
    ja : require('../components/locales/ja.json'),
  }
});

document.addEventListener('DOMContentLoaded', () => {
  const app = new Vue({
    i18n,
    vuetify,
    render: (h) => h(App),
  }).$mount();

  document.body.appendChild(app.$el);

  console.log(app);
});

locales/ja.json

モデルのenumを日本語に変えるjsonファイルになります。

{
      "analyzes": {
        "sake_strongness_types": {
            "weak": "下戸",
            "normal": "普通",
            "strong": "酒豪"
        },
        "next_nomivation_types": {
          "flesh": "しっぽり",
          "normal": "ほろ酔い",
          "strong": "酩酊"
                }
      }
}

表示させたいコンポーネントで、$t({{'表示させたい内容'}})のようにして表示させる事ができます。

{{ $t("analyzes.sake_strongness_types.strong") }}
# expected output : 酒豪

Result.vue

診断結果を表示する単一コンポーネントファイルになります。

<template>
  <div>
    <div class="text-center" style="font-size: 50px">
      <p>あなたの酒テータス</p>
      <v-card >
        {{ $t("analyzes.sake_strongness_types.strong") }} <img :src="beerSrc" width="150" height="100" />
       </v-card>
		</div>
  </div>
</template>
<!-- -- >

<script>
import { mapActions, mapGetters } from 'vuex';
export default {
computed{
...mapGetters('analyze', ['analyzes']),
imgSrc() {
      return require('../src/img/liquor.svg');
    },
created() {
    this.fetchAnalyzes();
    this.analyze = this.fetchAnalyzes;
  },
  methods: {
    ...mapActions('analyze', ['fetchAnalyzes']),
    ...mapActions('users', ['fetchAuthUser']),
  },
}
</script>

実際に出力される内容

Image from Gyazo

はじめよう | Vue I18n

【Vue】vue-i18n / 国際化 ~ 入門編 ~ - プログラム の超個人的なメモ