How to use Teleport in Vue 3?
Teleport is a built-in component in Vue 3 for rendering part of the template to other locations in the DOM. 1. It specifies the target position through the to attribute, such as body or #modal-container; 2. It is often used to solve display problems caused by the parent element overflow or z-index, etc.; 3. Events and responsiveness still work normally despite the DOM position change; 4. It is necessary to ensure that the target element exists, otherwise the content will not be rendered; 5. Pay attention to accessibility when using, such as focus management and ARIA attributes, and ultimately achieve a flexible layout that is separated from the component level.
Teleport is a built-in Vue 3 component that lets you render a part of your component's template into a different location in the DOM — typically outside the parent component's structure. This is especially useful for things like modals, toolstips, dropdowns, or notifications that need to be positioned at the top level (like body
) to avoid CSS clipping or z-index issues.

Here's how to use Teleport
in Vue 3:
✅ What Teleport Does
By default, components render within their parent's DOM structure. But sometimes, you want a child component (like a modal) to visually "break out" of its parent. That's where Teleport
comes in.

<template> <div class="modal-button"> <button @click="open = true">Open Modal</button> <!-- This will be moved outside the current DOM structure --> <Teleport to="body"> <div v-if="open" class="modal"> <p>This is a modal</p> <button @click="open = false">Close</button> </div> </Teleport> </div> </template> <script setup> import { ref } from 'vue' const open = ref(false) </script>
In this example, even though the <Teleport>
is nested inside .modal-button
, the modal content will be appended directly to the <body>
.
? Target Selector: to
Attribute
The to
prop specify where the content should be moved in the DOM.

<Teleport to="#modal-container"> <div class="modal">Hello from teleport!</div> </Teleport>
- Accepts any valid CSS selector:
body
,#app
,.modals
, etc. - Must point to an existing element in the DOM.
- If the target doesn't exist, the content won't render (no error by default).
? Tip: Use
body
for full-screen overlays like modals or loaders.
? Common Use Case: Modal Dialog
Here's a more realistic example of a reusable modal using Teleport
.
<!-- Modal.vue --> <template> <Teleport to="body"> <div v-if="show" class="modal-overlay" @click="onClose"> <div class="modal" @click.stop> <h3>{{ title }}</h3> <p>{{ message }}</p> <button @click="onClose">OK</button> </div> </div> </Teleport> </template> <script setup> defineProps({ show: Boolean, title: String, message: String, onClose: Function }) </script> <style> .modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 1000; } .modal { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.2); } </style>
Use it in a parent component:
<template> <div> <button @click="isModalOpen = true">Show Modal</button> <Modal :show="isModalOpen" title="Welcome" message="This is inside a teleport modal!" @close="isModalOpen = false" /> </div> </template> <script setup> import { ref } from 'vue' import Modal from './Modal.vue' const isModalOpen = ref(false) </script>
Even though Modal
is rendered inside this component, its content appears at the body
level — avoiding layout issues.
⚠️ Important Notes
- Events still work normally : Even after teleporting, event handlers and
v-model
bindings work because Vue maintains the reactive context. - Conditional rendering works : Use
v-if
orv-show
inside Teleport to control visibility. - Multiple Teleports : You can have multiple
<teleport></teleport>
components in one template, targeting different locations. - Accessibility : When using modals, remember to manage focus and ARIA attributes for screen readers.
✅ When to Use Teleport
- Modals, dialogs, or popups
- Tooltips and dropdowns (especially with overflow issues)
- Notifications or toast messages
- Full-screen loaders
It solves the classic problem: "My modal is cut off because of overflow: hidden
on a parent."
Basically, Teleport gives you DOM flexibility without breaking reactivity. It's clean, built-in, and very useful for UI components that need to escape their container. Not magic — just smart DOM rendering.
The above is the detailed content of How to use Teleport in Vue 3?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This article has selected a series of top-level finished product resource websites for Vue developers and learners. Through these platforms, you can browse, learn, and even reuse massive high-quality Vue complete projects online for free, thereby quickly improving your development skills and project practice capabilities.

The life cycle hook of the Vue component is used to execute code at a specific stage. 1.created: Called immediately after the component is created, suitable for initializing data; 2.mounted: Called after the component is mounted to the DOM, suitable for operating the DOM or loading external resources; 3.updated: Called when the data update causes the component to be re-rendered, suitable for responding to data changes; 4.beforeUnmount: Called before the component is uninstalled, suitable for cleaning event listening or timer to prevent memory leakage. These hooks help developers accurately control component behavior and optimize performance.

To implement reusable Vue paging components, the following key points need to be clarified: 1. Define props including the total number of lines, the number of lines per page and the current page number; 2. Calculate the total number of pages; 3. Dynamically generate the displayed page number array; 4. Process the page number click event and pass it to the parent component; 5. Add styles and interaction details. Receive data through props and set default values, use the computed attribute to calculate the total number of pages, use the method to generate the currently displayed page number array, render buttons in the template and bind click events to trigger the update:current-page event, listen to the event in the parent component to update the current page number, and finally highlight the current page number through CSS and control the button status to improve the user experience.

For Vue developers, a high-quality finished project or template is a powerful tool to quickly start new projects and learn best practices. This article has selected multiple top Vue free finished product resource portals and website navigation for you to help you find the front-end solutions you need efficiently, whether it is a back-end management system, UI component library, or templates for specific business scenarios, you can easily obtain them.

$ref is a keyword used to reference other parts of a JSON or YAML configuration file or external file structure, commonly found in JSONSchema and OpenAPI specifications. 1. The basic syntax of $ref is {"$ref":"path"}, which can point to the internal inside of the current document (such as #/definitions/User) or external files (such as user-schema.json#/definitions/User). 2. Usage scenarios include reusing schemas, splitting large files, and organizing code structures. 3. Note that the path must be correct, avoid circular references, ensure that external files are accessible, and avoid excessive nesting.

Using slots and named slots in Vue can improve component flexibility and reusability. 1. The slot allows the parent component to insert content into the child component through a tag, such as inserting paragraph text into the Card.vue component; 2. The named slot realizes control of the content insertion position through the name attribute, such as defining the header, body and footer areas respectively in the modal box component; 3. The default content can be set in the slot as an alternative when the parent component is not provided, such as the default close button; 4. The # symbol is the abbreviation syntax of v-slot:; 5. It is recommended to use slots reasonably to avoid excessive dependence, and some content can be considered to be implemented through props or scope components.

Install VueI18n: Vue3 uses npminstallvue-i18n@next, Vue2 uses npminstallvue-i18n; 2. Create language files such as en.json and es.json in the locales directory, supporting nested structures; 3. Create instances through createI18n in Vue3 and mount them in main.js, Vue2 uses Vue.use(VueI18n) and instantiate VueI18n; 4. Use {{$t('key')}} interpolation in templates, use useI18n's t function in Vue3Composition API, and Vue2Options API

Computed has a cache, and multiple accesses are not recalculated when the dependency remains unchanged, while methods are executed every time they are called; 2.computed is suitable for calculations based on responsive data. Methods are suitable for scenarios where parameters are required or frequent calls but the result does not depend on responsive data; 3.computed supports getters and setters, which can realize two-way synchronization of data, but methods are not supported; 4. Summary: Use computed first to improve performance, and use methods when passing parameters, performing operations or avoiding cache, following the principle of "if you can use computed, you don't use methods".
