Teleport is a new feature introduced in Vue 3. Teleport provides better control to developers on where exactly an element is rendered.
Get Teleporting
Let us create a new Vue 3 app to start playing around with teleport. We will use Vite, because it is 2021.
|
|
Provide a project name (teleport
) and select vue
as the template.
Install dependencies and start the app.
|
|
Navigate to http://localhost:3000
to see your new app.
Replace the <template>
section in src/components/HelloWorld.vue
.
|
|
Create a new component src/components/Messages.vue
-
|
|
Replace <template>
section in src/App.vue
-
|
|
We are just rearranging a couple of things and setting the stage for demonstrating teleport.
You will see output as expected -
This makes absolute sense -
- You create a component and build up UI with components
- You use the components in the parent component/view exactly in the place you need it
Teleport helps us to write code in a logical fashion but have more control over where the component is rendered.
For e.g., we can change the code in Messages.vue
to -
|
|
Now, change App.vue
to -
|
|
The third message is moved to the first position, i.e, the rendering of the component will be teleported to the tag with id startapp
.
You may in fact transport anything outside of the entire Vue render tree. For e.g., change index.html
to -
|
|
Where to use teleport?
Teleport offers a cleaner segregation from the “coding” side of things as compared to where a component/element is rendered.
Here are a couple of use cases where teleport can help-
- High degree of control over positioning of elements: Display elements like status bar always at the bottom of page - no matter where they are used. You are not constrained to code in those components at the very end
- Modals: You can have a conditional display of modal dialog anywhere in the app, but you may want to move it to end. Or, you may move a full-screen modal to the
body
tag and have a cleaner UI