LoginSignup
7
4

More than 3 years have passed since last update.

nuxt-i18nでno_prefixを使用する

Last updated at Posted at 2019-10-12

やったこと

  • nuxt用にvue-i18nを拡張したプラグイン、nuxt-i18nというプラグインがあったので使った
  • ルートにロケールプレフィックスを含まずに表示させる

前提

  • nuxtプロジェクトを作成済み
  • nuxt-i18nをインストール済み

nuxt.config.tsの設定

nuxt.config.ts
modules: [
    :
 'nuxt-i18n'
],
i18n: {
     :
  strategy: 'no_prefix', // ロケールプレフィックスを含まなくする
},

言語の切り替え方法

vue-i18nの拡張メソッド setLocale or setLocaleCookie を使用する。
ちなみに、nuxt-i18nをインストールだけで this.$i18n が使える。

index.vue

<template lang="pug">
template(v-for="locale in locales")
  .a(@click="changeLocale(locale.code)") {{$t('val')}}
</template>
<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator';

@Component
export default class Index extends Vue {
  /** 対応言語一覧を取得する */
  computed: {
    locales: {
      get () {
        return this.$i18n.locales;
      },
    },
  }

  /**
   * リロードあり
   * クッキーへ言語設定。リロード後、言語切替
  */
  changeLocale(locale: string) {
    this.$i18n.setLocaleCookie(locale);
    this.$router.go(0);
  }

  /**
   * リロードなし
   * クッキーと、$i18n独自ストアのlocaleに言語を設定する
   * 直接storeを書き換えるためリロードは不要
  */
  async changeLocale(locale): Promise<void> {
    await this.$i18n.setLocale(locale);
  }

これで、ルートにロケールプレフィックスを含まずに画面遷移などができる。
リロードの有無は、お好きな方で。

参考

7
4
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
7
4