Get current locale in page when using global transition
Environment
- Operating System:
Linux - Node Version:
v16.14.2 - Nuxt Version:
3.3.1 - Nitro Version:
2.3.1 - Package Manager:
[email protected] - Builder:
vite - User Config:
modules,css,i18n - Runtime Modules:
@nuxtjs/[email protected] - Build Modules:
-
Reproduction
Minimal StackBlitz https://stackblitz.com/edit/nuxt-starter-swfqqg?file=pages%2Findex.vue
Try to switch languages: When you switch language to English, locale.value is still 'cs' (see console) When you switch language to Czech, locale.value is still 'en' (see console)
Describe the bug
Hello there,
I am using transitions in my project and according to the documentation I have updated my layout like:
<template>
<Header />
<NuxtPage :transition="{
name: 'page',
mode: 'out-in',
onBeforeEnter
}" />
</template>
<script setup>
const { finalizePendingLocaleChange } = useI18n()
const onBeforeEnter = async () => {
await finalizePendingLocaleChange()
}
</script>
however if I print locale.value in my page component, it's value always corresponds to the previous locale.
How can I get the current locale value in my page please?
Thanks!
Additional context
No response
Logs
No response
This is a tricky one to me! Tried debugging and investigating. Couple of things I will mention:
- Especially with transitions, it is best you have one element on root, so wrap up the component in a div like so:
<template>
+ <div>
<Header />
<NuxtPage :transition="{
name: 'page',
mode: 'out-in',
onBeforeEnter
}" />
+ </div>
</template>
- I believe layouts are intended to be used with slots - so it would be ideal to have
<template>
<div>
<Header />
- <NuxtPage :transition=".." />
+ <slot />
</div>
</template>
So you should have a separate app.vue with NuxtLayout and NuxtPage elements with your transition logic there.
In fact, the Nuxt docs recommend to use app.vue if you have only a single layout (but I would think this is a minimal repro, so that's fine)
- I did see if the
switchLocalePathlinks being on the same component has an effect - it shouldn't and it doesn't so that's fine (though I wasn't able to see a declaration for it -const switchLocalePath = useSwitchLocalePath()). The tricky part is the ref change on transition since theconsole.warnstatement is on the outside, but something like this works (but this would also not be preferable since it is per-page):
// https://v8.i18n.nuxtjs.org/guide/lang-switcher#per-page-component-transition
// https://github.com/nuxt-modules/i18n/blob/4ff543efc52534ed9039b5341926caac433ca928/playground/pages/index.vue#L31
definePageMeta({
pageTransition: {
name: 'page',
mode: 'out-in',
onBeforeEnter: async () => {
const { finalizePendingLocaleChange, locale } = useNuxtApp().$i18n
await finalizePendingLocaleChange()
console.log('onBeforeEnter', locale.value)
}
}
})
I hope kazupon will be able to provide inputs on the soonest availability! 🙂
Same error, is there a solution ?