NuxtN
Nuxt8mo ago
Piskr

Nuxt-i18n language switcher

So I'm trying to setup localization for my app. Now I've used the provided setup from the docs and managed to get it working for one language. When I try to switch the language, I get a lot of warnings for missing keys in my locale messages.
Which is very strange as both of the language JSONs are exactly the same. So for a test I changed the config to use the other language as default and it works, but when switching the result is the same.

So this is how I setup in my nuxt.config:
  i18n: {
    lazy: false,
    defaultLocale: 'en',
    locales: [
      { code: 'en', name: 'English', file: 'en.json' },
      { code: 'sl', name: 'Slovenian', file: 'sl.json' }
    ]
  },


In my root folder I've created a new folder(s) i18n/locales/ with 2 json files, en.json and sl.json.

When I try to switch with:
async function changeLanguage(langCode: 'en' | 'sl') {
  const to = switchLocalePath(langCode)

  sidebarStore.setLanguage(langCode)

  locale.value = langCode

  await refreshData()

  //const path = switchLocalePath(langCode)
  if (to) {
    await router.push(to) 
  }

  // 4. close the menu
  showLanguageDropdown.value = false

  }


It loads, but it doesn't find any keys. Then I do a direct URL with the updated language path it does load the correct translations.
When using:
<NuxtLink :to="switchLocalePath('en')">EN</NuxtLink>
<NuxtLink :to="switchLocalePath('sl')">SLO</NuxtLink>


It does switch, but because there is no call for refreshData(), so the data is not translated.

So my question is how to correctly switch between translations?
Was this page helpful?