onscopedispose running even though both pages use the same layout with the same component inside?
I have a layout which includes my component. when navigating between two pages using the same layout my component inside that layout has onscopedispose run why is that? i expected it to remain since it's on both?
2 Replies
Hi @WiFi Plug. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
When navigating between pages in Nuxt 3, even if both pages use the same layout and the layout contains a shared component, the lifecycle of components inside the layout can behave differently than you might expect due to how Nuxt handles page transitions and the use of Vue's <Suspense>.
According to the Nuxt documentation, when you navigate between pages, the new page component is mounted before the previous one is unmounted, because <NuxtPage> uses <Suspense> under the hood. However, layouts themselves are only re-mounted if you switch to a different layout. If you stay on the same layout, the layout component (and its children) should persist, and their lifecycle hooks (like onUnmounted or onScopeDispose) should not run—unless something else is causing them to be recreated or destroyed, such as a change in the layout's key or a forced re-render.
If your component inside the layout is being disposed (onScopeDispose is running) even when navigating between pages that use the same layout, possible reasons include:
- The layout is being re-rendered due to a change in its key or some reactive prop.
- The component inside the layout is conditionally rendered or keyed in a way that causes it to be destroyed and recreated.
- There is a custom transition or suspense logic that affects the layout or its children.
The knowledge sources do not provide a direct explanation for this specific behavior, but they do clarify that layouts are meant to persist across pages unless a different layout is used, and that <NuxtPage> uses <Suspense>, which affects the timing of mounting and unmounting for page components, not layouts themselves. If your layout or its children are being disposed, check for dynamic keys or conditional rendering in your layout that might be causing this behavior. If you are using transitions or keepalive, also ensure they are configured correctly, as improper use can affect component persistence as well Docs: <NuxtPage> lifecycle Docs: Layouts.
If you can share the relevant code for your layout and the component, it may help pinpoint the exact cause.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
<@679734274840330384> Kapa.ai is still learning and improving, please let me know how I did by reacting below.