[Vuejs]-Locale keeps resetting between switching pages. Nuxt-i18n

3👍

according to this quote from nuxtjs/i18n docs

When using detectBrowserLanguage and wanting to persist locale on a route change, you must call one of the functions that update the stored locale cookie. Call either setLocaleCookie(locale) to persist just the cookie locale or setLocale(locale) to both persist the cookie locale and switch the route to the specified locale. Otherwise, locale might switch back to the saved one during navigation.

https://i18n.nuxtjs.org/lang-switcher

you should use $i18n.setLocale instead of changing the property locale
using setLocale will change the cookie that stores the chosen locale

in your case this code should work

<template>
  <div class="lang-dropdown">
    <select @change="(e) => $i18n.setLocale(e.target.value)">
      <option
        v-for="lang in $i18n.locales"
        :key="lang.code"
        :value="lang.code"
        onchange="changeLocale"
      >
        {{ lang.name }}
      </option>
    </select>
  </div>
</template>

1👍

Al-bimani’s answer is what it says in documentation. However it didn’t work for me. So I realized my mistake. I had a nuxt-link like this for example:

<nuxt-link to="/about"> // instead of this I started using this;
<nuxt-link :to="localePath('/about')">

Before localePath it was resetting the locale after navigation. After adding localePath in nuxt-link it simply navigates with the locale you change.

👤omerS

-1👍

Set in your nuxt config:

i18n: {
    ...
    strategy: 'no_prefix',
    ...
}

to prevent the switch when always working with the same URLs (so not with /en/foo and /de/foo but just /foo) to keep the locale between nuxt-links which you somewhere set by this.$i18n.setLocale('en'); before.

Leave a comment