Vue 3 is in beta and it’s subject to change.
Vue 3 is the up and coming version of Vue front end framework.
It builds on the popularity and ease of use of Vue 2.
In this article, we’ll look at how to use the teleport
component to render elements and components in a different location in the DOM.
Teleport
We can use the teleport
component to let us render parts of our Vue template in a location that’s different from its usual location in the DOM
This is handy for creating things like modals and overlays.
The DOM element that we want to render our items in must already exist.
Otherwise, we’ll get an error.
For example, we can write:
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
<teleport to="#footer">
<p>footer</p>
</teleport>
</div>
<div id="footer"></div>
<script>
const app = Vue.createApp({});
app.mount("#app");
</script>
</body>
</html>
We added the teleport
component to our template with the to
prop set to the selector to mount the content inside it.
Therefore, the div with ID footer
will hold the p element that’s inside the teleport
component.
Using with Vue components
If teleport
has a Vue component, then it’ll remain a child component of the teleport
‘s parent.
For example, we can write:
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
<teleport to="#modals">
<div>A</div>
</teleport>
<teleport to="#modals">
<div>B</div>
</teleport>
</div>
<div id="footer"></div>
<script>
const app = Vue.createApp({});
app.component("parent-component", {
template: `
<h2>parent</h2>
<teleport to="#footer">
<child-component name="james" />
</teleport>
`
});
app.component("child-component", {
props: ["name"],
template: `
<div>{{ name }}</div>
`
});
app.mount("#app");
</script>
</body>
</html>
We put the parent-component
in the root template of our app.
It has a teleport
that has to
set to #footer
.
So it’ll be rendered in the div with the ID footer
.
It has the child-component
inside it.
And that’ll be rendered inside div with ID footer
also.
Using Multiple Teleports on the Same Target
We can have multiple teleports with the same selector set as their to
prop value.
They’ll be rendered by in the order that they’re defined in.
For instance, if we have:
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
<teleport to="#footer">
<div>foo</div>
</teleport>
<teleport to="#footer">
<div>bar</div>
</teleport>
</div>
<div id="footer"></div>
<script>
const app = Vue.createApp({});
app.mount("#app");
</script>
</body>
</html>
Then the rendered result would be:
<div id="footer">
<div>foo</div>
<div>bar</div>
</div>
Conclusion
The teleport
component lets us render parts of a Vue template in a location that’s different from the usual location in the DOM.