Gabriel Caiana

How to Preserve Component State Between Routes with KeepAlive in Nuxt 3


Typically, when a page change occurs, components are destroyed and recreated. We can keep a component “running” using the keepAlive property, so Nuxt wraps it in the <KeepAlive> component for us.

Let’s assume we have this page that counts continuously:

// ~/pages/count.vue
<template>
  {{ count }}
</template>

<script setup>
const count = ref(0);
onMounted(() => {
  setInterval(() => count.value++, 1000);
});
</script>

Each time we navigate out and back to /count, this component is recreated, restarting the count back to zero each time.

If you set the <keepAlive> property on the NuxtPage component, it preserves the state of all child components:

// app.vue
<template>
  <NuxtPage keepalive />
</template>

Now, if we navigate to another page, the component will not be destroyed and will continue counting even while we are on other pages. It will only be destroyed on a complete page reload.

This also works for child routes, as long as the parent component that is rendering the NuxtPage with <keepAlive> is not destroyed by a page change.

We can also set the keepalive property in the definePageMeta instead of specifying it in the NuxtPage component, which will keep all child pages alive:

<template>
  <div>
    Mantendo vivo.
    <NuxtPage />
  </div>
</template>

<script setup>
definePageMeta({
  keepalive: true,
});
</script>

Finally, all child pages that have keepalive set to true in their definePageMeta will have their state preserved when switching between them, regardless of what is happening in the NuxtPage component or the parent page (if any).


Did you like the content? To further deepen your knowledge, I recommend reading the official guide on KeepAlive in Vue.js. Check it out at: Vue.js KeepAlive Guide.

If you have questions or want to exchange development ideas, feel free to contact me on LinkedIn or GitHub. It will be a pleasure to continue the conversation!