Nuxt.js 多言語対応Nuxt-i18nの簡単な使い方

Nuxt.js 多言語対応Nuxt-i18nの簡単な使い方

nuxt-i18nを利用して簡単に多言語対応を実現するサンプルコード

環境

  • OS  Ubuntu19.10
  • node v12.13.0
  • npm 6.12.1
  • Nuxt.js v2.10.2

nuxtインストール

nuxt-i18n-testという名前でプロジェクトを作成

 npx create-nuxt-app nuxt-i18n-test

UIにbulmaを選択

Choose UI framework Bulma

nuxt-i18nインストール

下記のコマンドでインストール

yarn add nuxt-i18n
or
npm i nuxt-i18n

nuxt-i18n使い方

利用方法も簡単。今回は英語、日本語、中国語で「Hello World」と「home」を表示します。

nuxt.config.jsのmodulesに下記を追加します

 modules: [
    // Doc: https://github.com/nuxt-community/modules/tree/master/packages/bulma
    '@nuxtjs/bulma',
    [
      'nuxt-i18n',
      {
        locales: ['en', 'jp', 'cn'],
        defaultLocale: 'en',
        vueI18n: {
          fallbackLocale: 'en',
          messages: {
            en: {
              greeting: 'Hello world!',
              home: 'home',
            },
            jp: {
              greeting: 'こんにちは世界',
              home: 'ホーム',
            },
            cn: {
              greeting: '你好 世界',
              home: '首页',
            }
          }
        }
      }
    ]
  ],

次にindex.vueを下記の通りに編集します。

<template>
  <div class="container">
    <div>
      <logo />
      <main>
        <h1>{{ $t('greeting') }}</h1>
        <h1>{{ $t('home') }}</h1>

        <nuxt-link
          v-if="$i18n.locale !== 'en'"
          :to="switchLocalePath('en')"
        >
          English
        </nuxt-link>

        <nuxt-link
          v-if="$i18n.locale !== 'jp'"
          :to="switchLocalePath('jp')"
        >
          日本語
        </nuxt-link>

        <nuxt-link
          v-if="$i18n.locale !== 'cn'"
          :to="switchLocalePath('cn')"
        >
          中国語
        </nuxt-link>
      </main>
    </div>
  </div>
</template>

<script>
import Logo from '~/components/Logo.vue'

export default {
  components: {
    Logo
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.title {
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: block;
  font-weight: 300;
  font-size: 100px;
  color: #35495e;
  letter-spacing: 1px;
}

.subtitle {
  font-weight: 300;
  font-size: 42px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}

.links {
  padding-top: 15px;
}
</style>

たったこれだけで、多言語対応が可能です。

yarn dev で起動して、ブラウザから http://プライベートIP:3000 にアクセスすると多言語対応がされています。