Home  >  Article  >  Web Front-end  >  Let’s talk about a useful feature in Vue3: Teleport

Let’s talk about a useful feature in Vue3: Teleport

青灯夜游
青灯夜游forward
2022-07-15 11:16:491812browse

Let’s talk about a useful feature in Vue3: Teleport

A new feature of ve3 has been discussed for some time, that is Portals (Portal), its function is to move the template HTML to a different DOM local methods. Portals is a common feature in React, and the portal-vue library can be used in Vue2. (Learning video sharing: vue video tutorial)

Vue3 provides Teleport to support this function.

Purpose of Teleport

The first thing I need to understand is when to use the Teleport feature.

When dealing with larger Vue projects, it is important to have a logical way to organize the code base. However, when dealing with certain types of components, such as modals, notifications, or prompts, the logic for the template HTML may be in a different file than where we want the element to be rendered.

In fact, many times it is much easier to manage these elements when handled completely separate from the DOM of our Vue application. All this is because dealing with the position, z-index and styling of nested components can be tricky due to dealing with the scope of all their parents.

This is where Teleport comes in handy. We can write template code in the component where the logic is, which means we can use the component's data or props. However, it is then rendered completely outside the scope of our Vue application.

Without using Teleport we would have to worry about event propagation passing logic from child components to the DOM tree, but now it's much simpler.

How Vue Teleport works

Suppose we have some child components in which we want to trigger pop-up notifications. As just discussed, it's simpler if the notifications are rendered in a completely separate DOM tree, rather than Vue's root #app element.

The first thing we need to do is open our index.html and add a <p before></p>

The above is the detailed content of Let’s talk about a useful feature in Vue3: Teleport. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete