Vue3 Fundamentals · Built-in Components

Render elsewhere with Teleport

Rendering content elsewhere with Teleport

Render elsewhere with Teleport

A dialog belongs at the end of the page, above everything else. Its markup, though, belongs next to the button that opens it. Keeping those two things together in the source is convenient; keeping them together in the DOM is not.

<Teleport> moves its content to another element in the page. You give it a to selector, and Vue renders the children there instead of in place:

<template>
  <Teleport to="#modal">
    <p>Hello from the modal</p>
  </Teleport>
</template>

The content still belongs to the component that wrote it. Data, events, and reactivity work exactly as before — only the DOM location changes. The target element must already exist when the component mounts, so a page usually has an empty <div id="modal"> waiting for it.

The Test creates a #modal element, mounts your component, and checks the teleported text landed inside that element. The starter renders the text in place, so the target stays empty and the Test fails.

Challenge

The modal text is rendering in place instead of in the modal container. Move it with <Teleport>: export an App component from App.vue that sends its <p> into the element with id modal.

The Test creates that element, mounts your component, and expects the text to be inside it. The starter renders the paragraph in place, so the target is empty and the Test fails.

App.vue
<script setup>
const message = 'Hello from the modal';
</script>

<template>
  <p data-test="modal">{{ message }}</p>
  <p data-test="inline">Inline content</p>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.