Vue Tip: Use Teleport to Render a Component in a Different Place
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, moving this part of the template elsewhere in the DOM, outside of the Vue app, would be preferable.
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 a global state or splitting this into two components:
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 Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Assign Handler for Uncaught Errors
Error monitoring is important in production, and we can use the errorHandler function to send errors to error tracking services.
Vue Tip: Automatic Global Registration of Base Components
We can use webpack to register our Vue.js base components globally.