Mokkapps Logo

Vue Tip: Use Teleport to Render a Component in a Different Place

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
January 09, 2022
1 Minuten Lesezeit
|
- Ansichten

The built-in Vue 3 Teleport component allows us to render HTML outside the Vue.js application. This can be useful to position modals, toast notifications, overlays, and more.

Sometimes, a component’s template belongs logically to the component itself. At the same time, from a technical point of view, it would be preferable to move this part of the template somewhere else in the DOM, outside of the Vue app.

A full-screen modal is a common scenario where you’d want to handle the modal’s logic inside the component, but it should be positioned at a completely different place.

Teleport provides a clean way to allow us to control under which parent in the DOM we want a piece of HTML to be rendered, without having to resort to global state or splitting this into two components:

<template>
  <teleport to="body">
    This will be appended to the body tag
  </teleport>
</template>

The to attribute should be a valid CSS selector outside the Vue application.

Read more about Teleport in the official documentation.



If you liked this tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github