vue.jsnuxt.jsvue-routervue-i18nnuxt-i18n

Vue-Router and i18n with Nuxt


I am transferring a project with a vue-router from Vue.js to Nuxt.js.

After hours of trying and googleing I managed to get everything to work but this one issue that I cant get to work: **Integrating i18n and vue-router with Nuxt.js **

Two problems I could not solve yet:

  1. How to properly update i18n.locale in my router.js file?
  2. How to tell nuxt-i18n that I am using my own router? It now obviously complains about every page that the Route with name 'XXX___en' does not exist.

In my plain vue project the following code works, and I can change the locale in router.js and it would propagate and update this.$i18n.

i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'

import termsHTML from './translations/terms'
import privacyHTML from './translations/privacy'
import imprintHTML from './translations/imprint'

Vue.use(VueI18n)

export const i18n = new VueI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages: { ... }
}

router.js

...
import {
  i18n
} from "@/plugins/i18n.js";
...
router.beforeEach((to, from, next) => {
// Set locale to new language
// I CANT GET THIS NEXT LINE WORING IN NUXT.JS
if (i18n.locale !== lang) i18n.locale = lang
...
}

Now in Nuxt I want to do the same. I imported the nuxt-i18n plugin like this in nuxt.config.js:

['nuxt-i18n', {
  seo: true,
  locales: [{
    code: 'en',
    name: 'πŸ‡ΊπŸ‡Έ',
    iso: 'en-US'
  },
  {
    code: 'de',
    name: 'πŸ‡©πŸ‡ͺ',
    iso: 'de-DE'
  }],
  defaultLocale: 'en',
  vueI18n: {
    locale: 'en',
    fallbackLocale: 'en',
    messages: translations
  }
}],

I tried the following in my router without success.

router.js

import nuxtConfig from "~/nuxt.config";
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// access the i18n module which is the second item in the modules array
// then take second item which is the config object and take the vueI18n property
let i18n = nuxtConfig.modules[1][1].vueI18n
...
if (i18n.locale !== lang) i18n.locale = lang

This does not error, but does also not work. Vue.use() is probably wrong here, as this registers a new component, I guess my code does not refer to the right i18n?

Thanks for any help


Solution

  • I now got the thing I wanted by doing the redirects not in the router file but in the NavBar.vue component which gets loaded allways. There you can access this.$i18n without a problem.