← All the recipes·Built into Vue
Tabs that keep what you typed
KeepAlive keeps the component instead of destroying it, and onActivated/onDeactivated tell you when it comes back and leaves.
Vue SFC
<script setup lang="ts">
import { onActivated, onDeactivated, ref } from "vue";
/* Inside KeepAlive the component isn't destroyed: it only pauses and resumes. */
const seconds = ref(0);
let timer: ReturnType<typeof setInterval> | undefined;
onActivated(() => (timer = setInterval(() => seconds.value++, 1000)));
onDeactivated(() => clearInterval(timer));
</script>
<template>
<p>Llevas {{ seconds }} s en esta pestaña (se pausa al salir).</p>
</template>
Vue SFC
<script setup lang="ts">
import { shallowRef } from "vue";
import Notes from "./Notes.vue";
import Timer from "./Timer.vue";
const tabs = { Notas: Notes, Reloj: Timer };
const current = shallowRef<keyof typeof tabs>("Notas");
</script>
<template>
<div role="tablist">
<button v-for="(_, name) in tabs" :key="name" role="tab" :aria-selected="current === name" @click="current = name">
{{ name }}
</button>
</div>
<KeepAlive>
<component :is="tabs[current]" />
</KeepAlive>
</template>