CS
CS
Explore posts from servers
NNuxt
Created by CS on 4/21/2024 in #❓・help
Route switching when using i18n setLocale doesn't work...?
Hey there Nuxt community! I've been having a problem with my Nuxt application, (seemingly after upgrading my Nuxt package from 3.11.1 to 3.11.2 - but I'm not sure if that's the sole reason....) My problem is that when I switch the locale for my webapp, I don't have a "re-route" to the new route (for example from english ("/") to german ("/de-DE"), it stays on "/"). My current code looks something like this (like I said, after various iterations of things that didn't appear to work)
<template>
<nav>
<div class="nav-icons">
<div
v-for="language in locales"
:key="language.code"
class="language"
:class="{ active: locale === language.code }"
@click.prevent.stop="onLocaleChange(language.code)"
>
<Icon :name="language.icon" />
<span>{{ language.name }}</span>
</div>
</div>
<div class="links">
<NuxtLink v-for="link in links" :key="link.to" :to="localePath(link.to)">{{ link.text }}</NuxtLink>
<NuxtLink :to="localePath({ path: '/', hash: '#sport-select' })">Sport Selection</NuxtLink>
</div>
</nav>
</template>

<script lang="ts" setup>
const { locale, locales, setLocale } = useI18n();
const localePath = useLocalePath();
const router = useRouter();
const localeRoute = useLocaleRoute();
const switchLocalePath = useSwitchLocalePath();

const onLocaleChange = async (l: string) => {
await setLocale(l);
const switchPath = switchLocalePath(l);
console.log(switchPath);
router.push({
replace: true,
path: switchPath,
});
};
<template>
<nav>
<div class="nav-icons">
<div
v-for="language in locales"
:key="language.code"
class="language"
:class="{ active: locale === language.code }"
@click.prevent.stop="onLocaleChange(language.code)"
>
<Icon :name="language.icon" />
<span>{{ language.name }}</span>
</div>
</div>
<div class="links">
<NuxtLink v-for="link in links" :key="link.to" :to="localePath(link.to)">{{ link.text }}</NuxtLink>
<NuxtLink :to="localePath({ path: '/', hash: '#sport-select' })">Sport Selection</NuxtLink>
</div>
</nav>
</template>

<script lang="ts" setup>
const { locale, locales, setLocale } = useI18n();
const localePath = useLocalePath();
const router = useRouter();
const localeRoute = useLocaleRoute();
const switchLocalePath = useSwitchLocalePath();

const onLocaleChange = async (l: string) => {
await setLocale(l);
const switchPath = switchLocalePath(l);
console.log(switchPath);
router.push({
replace: true,
path: switchPath,
});
};
I'm pretty sure that switchPath version used to work before I upgraded my Nuxt version.... But currently it doesn't anymore. The cookie value does get changed, but the site url doesn't, which sucks, cause when refreshing the page it will swap back to the original language (not the new one that it was supposed to use)... I'd really appreciate it if anyone could give me some pointers/things to try or knows any other tips! Thanks!
19 replies