I am trying to set up localization for my Nuxt frontend. Every time I switch to English and then move to an other subpage of my website it does reset back to German.
This is my LanguageSelector
<template>
<div class="lang-dropdown">
<select v-model="$i18n.locale">
<option
v-for="lang in $i18n.locales"
:key="lang.code"
:value="lang.code"
onchange="changeLocale"
>
{{ lang.name }}
</option>
</select>
</div>
</template>
This is my i18n config file
import de from '../locales/de.json'
import en from '../locales/en.json'
export default {
local: 'en',
fallbackLocale: 'de',
messages: { de, en },
strategy: 'prefix'
}
This is my buildModules section of the Nuxt.config.js
['nuxt-i18n',
{
defaultLocale: 'de',
seo: true,
locales: [
{
code: 'de',
name: 'Deutsch',
iso: 'de-DE'
},
{
code: 'en',
name: 'English',
iso: 'en-US'
}
],
vueI18n: i18n
}]
3
Answers
according to this quote from nuxtjs/i18n docs
https://i18n.nuxtjs.org/lang-switcher
you should use
$i18n.setLocale
instead of changing the propertylocale
using
setLocale
will change the cookie that stores the chosen localein your case this code should work
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:
Before localePath it was resetting the locale after navigation. After adding localePath in nuxt-link it simply navigates with the locale you change.
Set in your nuxt config:
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.