1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue i18nとは

Last updated at Posted at 2024-06-25

🏆 ゴール 🏆

Vue i18nについて簡単な理解と使用方法について知る

使用方法については動くかの検証をしていないので本ドキュメントでは実装における大体知識が理解できれば良い

i18nってなに?

https://zenn.dev/fujishiro/scraps/9ed19d1472363f の記事に書いてる通り

i18nとは、”Internationalization" (= 国際化対応) を意味する略語。
先頭の「i」と末尾の「n」、これらの間に入る18文字から取られた名称とのこと。

i18n = 国際化対応 ということらしい
なのでvueで国際化対応ができるパッケージと理解

前提

Vue 3.0以上が必要

できること

言語ごとにJSONデータを用意して多言語対応が可能

使い方(一例)

1.言語切り替え設定をJSONファイルに集約

必要な言語ごとにJSONファイルを作成

~/src/i18n/ja.json
{
  "message": {
    "hello": "こんにちは"
  }
}
~/src/i18n/en.json
{
  "message": {
    "hello": "Hello"
  }
}

2.main.js に組み込み

言語ファイルを読み込み、グローバルに使用可能とする

~/src/main.js
import { createApp } from "vue";
import App from "./App.vue";
import { createI18n } from "vue-i18n";
import ja from "./i18n/ja";
import en from "./i18n/en";

const i18n = createI18n({
  legacy: false,
  locale: "ja",
  messages: { ja, en },
});

createApp(App).use(i18n).mount("#app");

3.コンポーネントでの対応

$t(キー)で先程定義したキーに対応する文字列が得られます

~src/components/test.vue
<template>
  <div>
    {{ $t("message.hello") }}
  </div>
</template>

この場合には

  • 日本語の場合 "こんにちは"
  • 英語の場合 "Hello"

が表示される

言語切り替えについて

i18nのlocaleを変更することで可能

$i18n.locale = 'ja'; // 'ja'や'en'など

注意点

  • i18nの設定や使用には、Vueの公式ドキュメントなどを参照することが推奨されます
  • 実際のアプリケーションで使用する際は、動作確認やテストを行うことが重要です
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?