loading...

Nuxt 多言語化(en, ja)

ryunishimura profile image Ryu Nishimura ・1 min read

更新していくよ

ポイント

  • 英語と日本語のみ対応する
  • 同一URLで切り替える
  • Vuexで言語情報を持つ
yarn add vue-i18n
Enter fullscreen mode Exit fullscreen mode

@/plugins/i18n.js

import Vue from "vue"
import VueI18n from "vue-i18n"
Vue.use(VueI18n)
export default ({ app, store }) => {
  app.i18n = new VueI18n({
    locale: store.state.locale,
    fallbackLocale: "ja",
    messages: {
      ja: require("@/locales/ja.json"),
      en: require("@/locales/en.json"),
    },
  })
}
Enter fullscreen mode Exit fullscreen mode

@/mixins/common.js

export default {
  computed: {
    locale() {
      return this.$store.getters.locale
    },
  },

  watch: {
    locale(lang) {
      // ここで設定を切り替えている
      this.$i18n.locale = lang
    },
  },

Enter fullscreen mode Exit fullscreen mode

@/store/index.js

export const state = () => ({
  locales: ["en", "ja"],
  locale: "ja",
})

export const getters = {
  locale: (state) => {
    return state.locale
  }
}
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide