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 arbitrary positions 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 been lacking in Vue, requiring third-party libraries to implement. But in Vue3, we have a new built-in component called Teleport
- I call it the teleport panel (mistakenly).
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 destination. It moves the real DOM element, so the element's state is preserved.
disabled
is optional, used to disable the functionality. When set to true, it means that the content is not moved to the location specified by the to
parameter. By controlling the disabled
attribute, you can flexibly manipulate the default slot content, and dynamically changing it is similar to moving the real DOM element.
More detailed usage#
Just like Portal
, many use cases are similar, mainly for better control with Teleport
and 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.