For frontend developers using React, portals
should be quite familiar, allowing nodes to be rendered outside of the parent component.
This functionality of rendering nodes to any other position is very useful when developing custom components, especially for modal components or popup components. It allows parts of the content to be mounted to the body
, making the logic clearer and unaffected by the parent element, thus making the adjustment of parent element styles more flexible.
However, a similar feature has always been missing in Vue, and even requires third-party libraries to implement. But in Vue3, we have introduced a new built-in component called Teleport
- which I refer to as a teleport panel (mistake).
Teleport online!
Usage#
Like the built-in components Teleport
, Transition
, and KeepAlive
, we can use it in any Vue3 project as follows.
const app = Vue.createApp({
name: 'test',
template: `
<div class="text">
<div>Hello World</div>
<teleport to="body">
<span>this is teleport</span>
</teleport>
</div>
`,
})
const vm = app.mount('#app')
It will render the following structure
<body>
<div id="app" data-v-app="">
<div class="text">
<div>Hello World</div>
<!--teleport start-->
<!--teleport end-->
</div>
</div>
<span>this is teleport</span>
</body>
Component props#
The Teleport
component has only two props - to
and disabled
.
to
is required, used to specify a query selector or HTMLElement. This attribute can be modified by :
or v-bind
, and changes to the parameter will result in a change in the teleport target. It moves the real DOM element, so the element's state is also preserved.
disabled
is optional, used to disable the functionality. When set to true, it means that the content is not moved to the position specified by the to
parameter. By controlling the disabled
attribute, you can flexibly manipulate the default slot content, and dynamically changing it is also moving the real DOM element.
More detailed usage#
Just like Portal
, many use cases are the same, mainly Teleport
provides better control and is more suitable for Vue's template syntax.
Through this content-moving feature, we can more easily encapsulate Popover-type components that can be uniformly controlled. Moving the component content to the body node allows for better control of styles and avoids any unknown impacts on the original parent element.