You write the "Order placed!" modal inside the order card. A modal is a message box that appears on top of the page. When the Order button is clicked, the modal appears, but only as big as the card, with its edges cut off. Elsewhere in the app, a customer types the note "no vegetables" in the Food tab, moves to the Drinks tab for a moment, then comes back. The note is gone.
Vue has two built-in components for those two problems. Teleport renders part of a template somewhere else in the DOM, such as the modal straight into <body>. KeepAlive keeps a component that isn't showing right now, so its contents aren't lost when the tab changes.
Picture the cashier at Mrs. Sri's stall. The cashier writes an "order ready" notice at the desk, then pins it on the board at the front of the stall so everyone sees it. What the notice says is still the cashier's business. That's how Teleport works: the modal (the notice) is written in its component (the cashier's desk), but shows in <body> (the front board), and its data still belongs to that component. Then, when the cashier goes to serve another customer, a half-written order note goes into the drawer, not into the bin. That's how KeepAlive (the drawer) works: a component that's left (the half-written note) is kept with its contents, then taken out again when you come back.
Teleport: the modal moves to body
The "Order placed!" modal is written inside the order card, because the Order button, which opens the modal, is in that card. The problem is that the card has overflow: hidden and transform. A position: fixed modal inside it is trapped too: its size follows the card and the rest is cut off. This problem is like the stacking context problem in the z-index lesson. Teleport moves the modal's DOM into <body>, while its code stays in the card:
<script setup>
import { ref } from "vue"
const show = ref(false)
</script>
<template>
<div class="order-card">
<button @click="show = true">Order</button>
<Teleport to="body">
<div v-if="show" class="modal">
<p>Order placed!</p>
<button @click="show = false">Close</button>
</div>
</Teleport>
</div>
</template>
After Order is clicked, the DOM looks like this:
<body>
<div id="app">
<div class="order-card">
<button>Order</button>
</div>
</div>
<div class="modal">
<p>Order placed!</p>
<button>Close</button>
</div>
</body>
The modal is now directly inside <body>, outside the <div id="app"> that holds the Vue app.
totakes a CSS selector, such as"body"or"#modal-target".- Only the DOM moves. The logic still belongs to the component:
show,@click, props and provide/inject work as usual. - The target (the element
topoints at) must already be on the page when the component is mounted. Withto="#missing", in development mode the console writes[Vue warn]: Failed to locate Teleport target with selector "#missing"., and when the modal opens, an error appears. - If Vue itself renders the target in the same template, for example a
<div id="target">after the<Teleport>, adddefer(Vue 3.5 and later).<Teleport defer to="#target">waits until the whole template is mounted. We tried it on Vue 3.5.45: withoutdefer, the warning above appears and the content doesn't move. Withdefer, the content goes into#target. :disabled="true"makes Teleport render its contents in their original place. An example is a modal that is meant to show inside the card on a small screen.- In the first exercise, you make an
#openbutton and a<div id="modal">holding "This is a modal!" plus a Close button. That modal div is wrapped in<Teleport to="body">. The checker opens the modal and looks forbody > #modal(a#modaldirectly inside<body>), so a modal left inside its component doesn't pass.
KeepAlive: a tab that doesn't forget
This is an app with two tabs, Food and Drinks. FoodTab has a note field, and writes to the console every time one of its lifecycle hooks runs:
<!-- App.vue -->
<script setup>
import { ref } from "vue"
import FoodTab from "./FoodTab.vue"
import DrinksTab from "./DrinksTab.vue"
const tab = ref("food")
const tabs = { food: FoodTab, drinks: DrinksTab }
</script>
<template>
<button @click="tab = 'food'">Food</button>
<button @click="tab = 'drinks'">Drinks</button>
<KeepAlive>
<component :is="tabs[tab]" />
</KeepAlive>
</template>
<!-- FoodTab.vue -->
<script setup>
import { ref, onMounted, onUnmounted, onActivated, onDeactivated } from "vue"
const note = ref("")
onMounted(() => console.log("mounted"))
onUnmounted(() => console.log("unmounted"))
onActivated(() => console.log("activated"))
onDeactivated(() => console.log("deactivated"))
</script>
<template>
<p>Fried Rice $15, Chicken Noodles $12</p>
<input v-model="note" placeholder="Note" />
</template>
This table shows what the console writes at each step, without and with KeepAlive, then what the note field holds at the end:
| Step | Without KeepAlive | With KeepAlive |
|---|---|---|
| The Food tab shows | mounted |
mounted, activated |
| Type "no vegetables", move to Drinks | unmounted |
deactivated |
| Back to Food | mounted |
activated |
| What the note field holds | empty | no vegetables |
Without KeepAlive, the note field is empty. FoodTab is unmounted when it's left, just like a component removed by v-if in the Lifecycle Hooks lesson. When you come back, what shows is a new FoodTab with a new note.
<component :is="tabs[tab]">renders the component picked through thetabdata:tabs[tab]isFoodTaborDrinksTab. Changetab, and the component changes.- Inside KeepAlive, a component that's left is kept, not destroyed.
onDeactivatedruns when the component is left, andonActivatedwhen you come back (and also once after the firstonMounted).onMounteddoesn't run again. v-if/v-elsebetween two components also works inside KeepAlive, as long as only one component shows.- In the second exercise, you make a smaller version of the example above:
FoodTabholds<input id="note">,DrinksTabholds#drinks, and<KeepAlive>wraps<component :is="activeTab === 1 ? FoodTab : DrinksTab" />. The checker typesno vegetables, switches to Drinks, comes back, then reads the note.
include and max
<KeepAlive include="FoodTab">keeps only the component named FoodTab. The other components are still unmounted. A component's name comes from thenameoption in the component. A<script setup>component uses its file name: FoodTab.vue becomes FoodTab.includecan also be an array::include="['FoodTab', 'DrinksTab']".excludeis the opposite: the components it names are not kept.:max="2"keeps at most 2 components, including the one showing. When a third tab opens, the component left unopened the longest is unmounted.
⚠️ A modal with nowhere to go, and a tab that still forgets
- The Teleport target has to exist already: the selector points at an element that's there before the component is mounted, ideally outside the Vue app, like
body. - Teleport doesn't change the logic. It only moves the DOM. Props, events and data still belong to the component that wrote them.
- A component kept by KeepAlive isn't mounted again when you come back to its tab, so don't wait for
onMounted. UseonActivated. - The name in
includemust match the component's name exactly, capital letters included. - Every kept component still uses memory. Limit how many with
max.
TL;DR: <Teleport to="body"> renders its contents somewhere else in the DOM, usually <body>, so a modal (a message box on top of the page) isn't trapped by its parent's overflow or transform. The logic still belongs to the component, the target (the element to points at) must already exist, and disabled puts the contents back in their original place. <KeepAlive> keeps a component that's left, so state like a field's contents is still there when you come back. Without KeepAlive, the component is unmounted and its state is lost. A kept component uses the hooks onActivated (when it shows again) and onDeactivated (when it's left), because onMounted doesn't run again. include picks which components are kept, max limits how many.
⚡ Teleport: the modal moves to body
Write:
<div class="order-card">
<button @click="show = true">Order</button>
<Teleport to="body">
<div v-if="show" class="modal">
<p>Order placed!</p>
<button @click="show = false">Close</button>
</div>
</Teleport>
</div>
Meaning: A modal is a message box that appears on top of the page. If the .order-card card uses overflow: hidden or transform, a modal inside it is trapped too and gets cut off. Teleport renders its contents somewhere else in the DOM, here straight into <body>, so the modal shows in full. Only the DOM moves: show and @click still belong to this component.
⚡ KeepAlive: a tab that doesn't forget
Write:
<KeepAlive>
<component :is="tabs[tab]" />
</KeepAlive>
Guess first: tabs[tab] is the tab component that's picked now, Food or Drinks. Without KeepAlive, a customer types "no vegetables" in the note field of the Food tab, moves to Drinks, then comes back. Is the note still there?
It's gone. The Food tab's component (FoodTab) is unmounted when it's left. What shows when you come back is a new FoodTab with an empty note field.
Meaning: <component :is="tabs[tab]"> shows the component that the tab data picks. The <KeepAlive> around it keeps a component that isn't showing, with its state, instead of destroying it. So the field's contents are still there when you come back.
⚡ onActivated, not onMounted again
Write:
onActivated(() => console.log("activated"))
onDeactivated(() => console.log("deactivated"))
Meaning: A component kept by KeepAlive isn't mounted again when its tab is opened again, so onMounted doesn't run again. onDeactivated runs when the component is left, and onActivated when you come back.