8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue.js】vue-i18nを使って多言語化

Posted at

vue.js備忘録、第三弾。
業務で多言語対応するのに使っている技術なので、勉強の為に。

i18nとは

広くは「国際化」という事。internationalizationの先頭iと語尾nの間に18文字がある事からそう呼ばれているとか。読み方は色々あるようですが「あいじゅうはちえぬ」でも間違いではないみたい。

vue-i18nというライブラリを使う

今回はVue.jsでの導入。こちらのライブラリを使用します。

導入

まずはライブラリをインストール

npm install vue-i18n

しっかり読み込む記述をします。

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

Vue.use(VueI18n);
const i18n = new VueI18n({
  locale: 'ja',
  messages: {
    // 翻訳用のjson
    ja : require('../lang/ja.json'),
    en : require('../lang/en.json'),
    cn : require('../lang/cn.json'),
    tw : require('../lang/tw.json')
  }
});

const app = new Vue({
  el: '#app',
  i18n: i18n,
  components: {
  }
})

翻訳ファイルはjsonで書きます。

ja.json
{
  "ログイン" : "ログイン",
  "会員登録" : "会員登録",
}
en.json
{
  "ログイン" : "login",
  "会員登録" : "sing up",
}

$tメソッドを使って書く事で翻訳が適用出来るようになります。簡単だね。

nav.vue
<div>
  <p class="login">{{ $t("ログイン") }}</p>
  <p class="sing_up">{{ $t("会員登録") }}</p>
</div>

vueだけで言語切り替えするだけならこれも簡単なのですが、
laravelと連携させて、どっちも変更するみたいな動きをさせたい。出来たらまた記事にします。

8
6
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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?