LoginSignup
6
4

More than 3 years have passed since last update.

Vue I18nを使って多言語サイトを作成する

Last updated at Posted at 2020-01-28

Vue I18nを使って英語・日本語の対応のサイトを作成しましたので、簡単に使い方を紹介します。

インストール

npm install vue-i18n

2020年1月28日現在でのバージョンはv8.15.3です。

ディレクトリ構成

global.jsonはサイト全体で使用するサイト名や、ヘッダーメニューなどのテキストです。
errors.jsonはバリデーションエラー時の汎用メッセージを置いています。エラーメッセージを使わないコンポーネントもあるので、globalと分けています。
components、containersの各コンポーネントに対して1ロケールファイルを用意しています。

.
├── main.ts
├── components
│   └── Hello.vue
├── containers
│   └── Hello.vue
└── locale
    ├── global.json // グローバルのロケールメッセージ
    ├── errors.json // コンポーネントの共有ロケールメッセージ 
    ├── components
    │    └── hello.json
    └── containers
         └── hello.json

コード例

main.ts
import Vuei18n from 'vue-i18n';

Vue.use(Vuei18n);
const i18n = new Vuei18n({
  locale: "ja",
  messages,
});

new Vue({
  i18n,
  render: (h) => {
    return h(App);
  },
}).$mount('#app');
global.json
{
    "ja":{
        "title": "きーた",
        "menu": {
            "home": "ホーム",
            "about": "XXXについて",
        }
    },
    "en":{
        "title": "Qiita",
        "menu": {
            "home": "HOME",
            "about": "About",
        }
    }
}
hello.json
{
    "ja":{
        "title": "きーた",
    },
    "en":{
        "title": "Qiita",
    }
}
errors.json
{
  ja: {
    errors: {
      notFound: "{msg}が見つかりませんでした"
    }
  }
  en: {
    errors: {
      notFound: "{msg} is not found"
    }
  }
}
hello.json
{
  ja: {
    message: {
      hello: "こんにちは、世界"
    }
  }
  en: {
    message: {
      hello: "hello world"
    }
  }
}
Hello.vue
<template>
  <div>
    <h1>{{ $t("title") }}</h1>
    <p>{{ $t("message.hello") }}</p>
    <p>{{ $t("error.notFound", { msg: "XXX" }) }}</p>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import sharedMessages from '@/locale/errors.json';
import messages from '@/locale/components/hello.json';

export default Vue.extend({
  name: 'Hello',
  props: {
    ...
  },
  data() {
    ...
  },
  i18n: {
    messages,
    sharedMessages,
  },
});
</script>

グローバル以外の共通メッセージ

グローバルメッセージであればどこからでも参照可能ですが、エラーメッセージのような全コンポーネントから参照が必要のないメッセージは sharedMessages を使います。

カスタムブロック

単一ファイルコンポーネントの場合はカスタムブロックで管理することもできます。
https://kazupon.github.io/vue-i18n/guide/sfc.html#basic-usage

XXX.vue
<i18n>
{
  "en": {
    "hello": "hello world!"
  },
  "ja": {
    "hello": "こんにちは、世界!"
  }
}
</i18n>

さいごに

ディレクトリ構成、グローバルロケール・共通ロケール・ローカルロケールについて紹介されてる記事は見当たらなかったので、この記事が参考になれば幸いです。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4