Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 87 ยท Reusability, Transitions and Styling

Teleport and KeepAlive

Render modals outside their parent with Teleport, keep component state alive with KeepAlive, and get a quick tour of every built-in component Vue ships with.

Most of the time a component's output stays exactly where its template puts it: a <div> inside a component ends up inside the parent's DOM node. That is usually what you want, until you build a modal dialog. A modal must cover the whole screen, but its component may sit deep inside a card that has overflow: hidden, a CSS transform, or a low z-index. Any of those can clip the dialog or trap it behind other content.

Vue solves this with the built-in <Teleport> component, which renders its children somewhere else in the DOM while keeping them part of the same component tree. This lesson also covers <KeepAlive>, which keeps a component's state alive while it is switched out, and finishes with a recap of all built-in components.

All examples load Vue from a CDN, as in Your First Vue App. We use the build that includes the template compiler (vue.esm-browser.prod.js), so string templates work. In a project with a build step, your .vue files are compiled ahead of time and you import from vue normally.

The problem: positioned ancestors trap fixed elements

position: fixed normally means "relative to the viewport". But if any ancestor has a transform, filter or perspective, that ancestor becomes the reference box for fixed children. An overflow: hidden ancestor clips them too. A modal declared inside such a container looks broken, even though the CSS on the modal itself is perfect.

You could move the modal's markup to the end of <body> by hand, but then the modal's template is no longer next to the button that opens it, and it cannot share the component's state easily. <Teleport> gives you both: you write the markup where it belongs logically, and Vue mounts the DOM nodes where they work best.

How Teleport works

HTML
<Teleport to="body">
  <div class="dialog">I am rendered as a child of body</div>
</Teleport>

The to prop takes a CSS selector string or a real DOM element. When the component renders, Vue creates the children and inserts them into the target. Where the <Teleport> itself would have been, Vue leaves an empty placeholder comment so it can find its place again.

The important idea is that teleporting changes the DOM, not the component tree. The teleported content is still a child of the component that wrote it:

  • It can read that component's state and call its methods.
  • Props and events flow the normal way, and provide/inject still work (see Provide and Inject).
  • When the parent is unmounted, the teleported content is removed with it.
  • Vue DevTools shows it under the original parent.
flowchart LR
  subgraph tree["Component tree (what you write)"]
    A["App"] --> B["Card"]
    B --> C["Teleport"]
    C --> D["Dialog content"]
  end
  subgraph dom["DOM tree (what the browser sees)"]
    E["body"] --> F["#app with Card"]
    E --> G["Dialog content"]
  end
  D -.->|"moved to"| G

The component tree keeps the dialog under Card; the DOM puts it directly under body.

Props of Teleport

  • to (required): the target selector or element. The target must exist in the DOM when <Teleport> mounts, which is why people usually pick body or an element placed before the app's script runs.
  • disabled: when true, the content is rendered in place, as if there were no Teleport. You can switch it at runtime, and Vue moves the nodes.
  • defer (Vue 3.5+): waits until the end of the current render tick before resolving to. Use it when the target element is rendered by the same app and appears later than the Teleport.

Several teleports can share one target. Their content is appended in mounting order, which is handy for a notification area that many components write into.

Example: a modal that escapes its container

The card below has overflow: hidden and a transform, the two things that break a fixed-position dialog. The checkbox flips the disabled prop, so you can compare both behaviors with the same markup. Open the modal with Teleport on, then off.

Teleport on and off

With Teleport on, the dark backdrop covers the whole preview. With it off, the same modal is squeezed into the dashed card and clipped. Nothing else changed: only where Vue put the nodes.

A reusable modal component

In a real app you wrap this pattern once and reuse it. The component below renders its slot into a dedicated #modal-root element, closes on the Escape key, and tells its parent to close through an event. It uses props, emits and slots you met in Props, Events and emits and Slots.

A reusable AppModal

The dialog's text reacts to the parent's name state even though its DOM lives in #modal-root, which proves the component tree is intact. Change the name while the dialog is open (click into the input behind the backdrop is blocked, so open, close, edit, and reopen). The line under the button reports the real DOM parent.

A modal needs more than a Teleport to be accessible: it should move focus into the dialog, trap Tab inside it, and return focus to the trigger when closed. The role and aria-modal attributes above are only a start. Accessibility in Vue shows the full pattern.

KeepAlive: remember state while a component is away

Switching between components with <component :is="..."> destroys the old component and creates the new one, so anything the user typed or counted is lost. Wrap the dynamic component in <KeepAlive> and Vue instead deactivates it: the instance, its state and its DOM are cached, and it is reactivated when the user comes back.

HTML
<KeepAlive>
  <component :is="currentTab"></component>
</KeepAlive>

<KeepAlive> accepts exactly one child at a time and works with v-if / v-else chains and dynamic components. It has three props:

  • include: only cache components whose name matches. It accepts a comma-separated string, a regular expression, or an array of either.
  • exclude: never cache components whose name matches. exclude wins when both match.
  • max: the largest number of cached instances. Beyond it, Vue destroys the least recently used one.

Names are matched against the component's name option (in an SFC using <script setup>, the name is inferred from the file name).

flowchart TD
  S["User switches to tab B"] --> Q{"Does tab A pass<br/>include and exclude?"}
  Q -->|"yes"| K["Deactivate A and keep it in the cache"]
  Q -->|"no"| U["Unmount A, its state is lost"]
  K --> M{"More than max instances?"}
  M -->|"yes"| R["Unmount the least recently used"]
  M -->|"no"| D["Done"]

A deactivated component stays in memory; include, exclude and max decide what is allowed to stay.

Two extra lifecycle hooks

Cached components do not run onMounted again when they return. Use onActivated (runs on first mount and every time it is re-inserted) and onDeactivated (runs when it is removed into the cache) for work that must follow visibility, such as pausing a timer or refreshing stale data. They work for the cached component and for all components inside it.

KeepAlive keeps the counter

Try this: click the counter a few times, press About, then Counter. With the checkbox ticked the count survives and the log shows "deactivated" and "activated". Untick the box and repeat: the counter restarts at 0 and the log shows "unmounted".

Do not use KeepAlive everywhere. Every cached instance stays in memory with its watchers and DOM. Cache the screens whose state is expensive to rebuild (a half-filled form, a scroll position, a loaded list) and give the cache a sensible max.

Built-in components at a glance

Teleport and KeepAlive are two of the five components Vue provides without any import or registration. They are special: the compiler knows them, and you cannot write them as ordinary user components.

Component What it does Where to learn more
<Transition> Animates one element or component entering or leaving Transition Component
<TransitionGroup> Animates items of a list as they enter, leave and move TransitionGroup and List Animation
<KeepAlive> Caches inactive component instances This lesson
<Teleport> Renders content in another place in the DOM This lesson
<Suspense> Shows fallback content while async dependencies resolve Experimental

<Suspense> coordinates components with async setup() or top-level await, and async components. It is still marked experimental in Vue 3.5, so its API may change. Most apps handle loading with explicit state (see Fetching Data) and defineAsyncComponent (see Dynamic and Async Components).

Notice that <component> and <slot> also look like components, but they are compiler features, not built-ins you can pass props to in the same way.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does <Teleport to="body"> change?

    Teleport moves DOM nodes. The component tree is unchanged, so props, events, provide/inject and cleanup behave as if the content stayed in place.
  2. 2. A modal inside a parent with a CSS transform is clipped. What is the cleanest fix?

    A transform makes the parent the containing block for fixed children, and z-index cannot escape it. Moving the nodes out with Teleport avoids the problem.
  3. 3. Which statement about KeepAlive's props is correct?

    max applies an LRU policy. include and exclude match component names, exclude wins on a conflict, and KeepAlive renders one child at a time.
  4. 4. A cached component should refresh its data every time the user returns to its tab. Which hook fits?

    A cached component is not mounted again, so onMounted runs only once. onActivated runs on the first mount and on every re-insertion from the cache.

Summary

  • <Teleport to="..."> renders its children elsewhere in the DOM while they remain part of the same component tree.
  • Use it for modals, toasts and tooltips that must escape overflow, transform or stacking contexts. disabled turns it off and defer waits for a late target.
  • Several Teleports can feed one target, and the target must exist when Teleport mounts (unless you use defer).
  • <KeepAlive> caches deactivated components so their state and DOM survive switching; include, exclude and max control the cache.
  • Use onActivated and onDeactivated for work tied to a cached component becoming visible or hidden.
  • Vue's built-ins are <Transition>, <TransitionGroup>, <KeepAlive>, <Teleport> and the experimental <Suspense>.
  • A teleported modal still needs focus handling and keyboard support to be accessible.

Next: Scoped CSS and CSS Modules