LoginSignup
165
152

More than 5 years have passed since last update.

Vue.jsではじめる多言語対応

Last updated at Posted at 2017-08-02

調べながら書いたので間違っていたらスミマセンmm

方法 / 前提

  • フロントのFWはVue.jsを採用。
  • 言語対応の方法としてi18nという国際規格を採用。
    • Vue.jsのi18nプラグイン -> https://github.com/kazupon/vue-i18n
      ( ※ kazuponさんという日本のVue.js界隈で有名な方が作成したものを推奨 / こまめにメンテされている)

具体的な書き方

サンプルがたくさんあるので、下記を見ればすぐ分かる
https://github.com/kazupon/vue-i18n/blob/dev/examples/

vue.script.js
import Vue from 'vue';
import VueI18n from 'vue-i18n';

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

// 言語の設定
Vue.use(VueI18n);
const i18n = new VueI18n({
  locale: 'ja', // デフォルト言語はjaにしておくが、ブラウザの言語を拾ってきてここに入れる => 言語変更されたら書き換える
  messages: data
});

// Vueたん
const app = new Vue({
  el: '#app',
  i18n: i18n,
  data: {},
  created() {},
  methods: {
    handleClick_changeLanguage(lang) {
      this.$i18n.locale = lang;
    }
  }
});

翻訳用のjsonファイル

json形式で言語ファイルを作り、言語はここで管理する。
基本的に1ページに対し、1jsonファイルがベスト。(検討中)
jsonデータはサーバ側から貰ってもよい。

message.json
{
  "ja": {
    "message": {
      "title": "タイトルだよーん",
      "subtitle": "ここがサブタイトルになります"
    }
  },
  "en": {
    "message": {
      "title": "title dayo-n",
      "subtitle": "sub title dayo-n"
    }
  },
  "han": {
    "message": {
      "title": "標題",
      "subtitle": "副標題"
    }
  }
}

en.jsonja.jsonのように言語ごとに分けることもできるし、
上記例のmessage.jsonのように英語と日本語を1ファイルで管理することも可能。

component.htmlはこんな感じ

app.component.html
<div id="app">
  <header class="header">
    <div>
      <p class="header__sub-text">{{ $t("message.subtitle") }}</p>
      <h1 class="header__title">{{ $t("message.title") }}</h1>
    </div>
  </header>

  <nav>
    <ul>
      <li><a href="#" v-on:click.prevent="handleClick_changeLanguage('en')">英語</a></li>
      <li><a href="#" v-on:click.prevent="handleClick_changeLanguage('ja')">日本語</a></li>
      <li><a href="#" v-on:click.prevent="handleClick_changeLanguage('han')">繁体字</a></li>
    </ul>
  </nav>
</div>

追記

vue-i18n for Server-Side Rendering も併せて使うと良さそう
https://github.com/kazupon/vue-i18n/tree/dev/examples/ssr

165
152
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
165
152