1
2

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 5 years have passed since last update.

Vuei18nで多言語化対応

Posted at

せしまるです。

今回はVue.jsを使ったアプリで多言語化対応したのでその備忘録として書きます。

#環境
Vue.js
TypeScript
fuse.js

#実装

まずVueI18nをインストールします

$ npm install vue-i18n

tsconfig.jsonに下記記述を追記します。

tsconfig.json
{
    "compilerOptions": {
                
        "resolveJsonModule": true
                
    }
}

fuse.jsでJSONPluginを読み込みます。

fuse.js
const { ..., JSONPlugin } = require("fuse-box");
                
                
context(
    class{
        config(name, template){
                
            plugins: [
                JSONPlugin(),
                

ここまでで準備はOK
jsonファイルを用意。
今回は日本語(ja)と英語(en)の2種類
私の環境ではassets/json/language.jsonとなってます。

language.json
{
    {
        "ja": {
            "mypage":{
                "title": "タイトル"
            }
        },
        "en": {
            "mypage":{
                "title": "タイトル"
            }
        }
    }
}

次にi18n.tsを作成。
私の環境ではcore/i18n.tsとなってます。

i18n.ts
import Vue from "vue"
import VueI18n from "vue-i18n"
import json from "../assets/json/language.json"
Vue.use(VueI18n)

export const i18n = new VueI18n({
    locale: "ja",
    messages: (<any>json)
})

使う側は先ほど作成したi18n.tsを読み込んで使います。
※一部省略してます.

mypage.vue
<template>
    <div>
        <p>{{geti18n("mypage.title")}}</p>
    </div>
</template>

<script>
import { i18n } from "../core/i18n"

export default class MyPage extends Vue{
        
    geti18n(name: string) : string{
        return i18n.tc(name)
    }
        
}
</script>

言語を切り替える際はi18n.localeに"en"や"ja"などjsonで定義した名前を入れると切り替わります。

#感想
私の環境ではVue-cliとかは特に使ってなかったので、かなりの数の記事を読んでここに行き着きました…(あとは先輩のお力を借りて)

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?