Table of Contents
App.vue
contains a component, then the component always maintains a logical parent-child relationship with the component that uses
04-如何禁用 Teleport
05-多个 Teleport 共享目标时
总结
Home Web Front-end Vue.js An in-depth explanation of how to use the Teleport component in Vue

An in-depth explanation of how to use the Teleport component in Vue

Apr 04, 2023 pm 07:28 PM
vue

How to use Teleport component in Vuejs? The following article will show you how to use the Teleport component in Vue. I hope it will be helpful to you!

An in-depth explanation of how to use the Teleport component in Vue

In components with a relatively complex DOM structure and deep hierarchical nesting, some logic needs to be processed based on the corresponding module business. This logic It belongs to the current component

but from the view of the entire page application, it should be rendered in DOM elsewhere outside the entire vue application and cannot affect the component. The structure of In the component, the event bound to the element maintains a certain correlation with the specific

DOM

element structure to be controlled in the same component and at the specific location. [Related recommendations:

vuejs video tutorial

, web front-end development] without deliberately separating some DOM structures, however, In the same component, the button that triggers the modal box and the modal box itself are in the same component

Because they are both associated with the switch state of the component, the modal box and the button are rendered together in the application Where the DOM structure is very deep, it will be very difficult to control the css layout position of the modal box

In view of such scenarios and difficulties,Vueofficially provides a

Teleport

Components can solve this problem very well, so that developers don’t need to worry about the structure of DOM##01-When the component hierarchy of components is very deepFor example: Now there are two components, the parent component and the child component. In the descendant component, add a button to pop up a modal box and let it display vertically and horizontally in the center of the page.

As shown below, the parent component As shown below

App.vue

<template>
    <div class="App">
        我是父组件
        <Child />
    </div>
</template>
<script setup>
    import Child from "./Child.vue"
</script>
<style>
.App {
    width: 400px;
    height: 400px;
    background:red;
}
</style>
Copy after login

The following is the

Child component, the sample code is as followsChild.vue

, we need to Descendants) component, add a button, click the button, a pop-up box will pop up, displayed horizontally and vertically in the center of the page

<template>
    <div class="child">
      <p>我是子组件</p>
        <button @click="isModel=true">打开模态框</button>
        <div class="mask-dialog" v-if="isModel">
             <div class="box">
                  <h2>我是标题</h2>
                  <div>我是弹框内容</div>
                  <div>
                      <button @click="isModel=false">关闭</button>
                  </div>
             </div>
        </div>
    </div>
</template>
<script setup>
import { ref } from "vue";
let isModel = ref(false);
</script>
<style>
.child {
    width: 300px;
    height:300px;
    background:green;
}
/**灰色遮罩层 */
  .mask-dialog {
    width: 100%;
    height:100%;
    position:absolute;
    left:0;
    top:0;
    background:rgba(0,0,0,0.5)
  }
  
  .box {
    width: 200px;
    height:200px;
    position:absolute;
    left:50%;
    top:50%;
    transform:translate(-50%,-50%);
    background:pink;
    text-align:center;
  }
</style>
Copy after login
There is a button button in the above sub-component to trigger the opening of the current component The modal box contains the logic to control the display and hiding of the pop-up box. When the nested components are deep and complex

If the parent element has positioning, then when controlling the position of the child element, Using

css's transform

or

position:absolute to refer to changes in the object will destroy the layout structure and some cssstyles## will appear. #Control problems will be very painful to solveThis Teleport component is to solve this type of problem. You can specify the

DOM

structural fragment , independent of going outside the component and not affected by the current component layout structure

After modification by Teleport<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;template&gt; &lt;div class=&quot;child&quot;&gt; &lt;p&gt;我是子组件&lt;/p&gt; &lt;button @click=&quot;isModel=true&quot;&gt;打开模态框&lt;/button&gt; &lt;Teleport to=&quot;body&quot;&gt; &lt;div class=&quot;mask-dialog&quot; v-if=&quot;isModel&quot;&gt; &lt;div class=&quot;box&quot;&gt; &lt;h2&gt;我是标题1&lt;/h2&gt; &lt;div&gt;我是弹框内容&lt;/div&gt; &lt;div&gt; &lt;button @click=&quot;isModel=false&quot;&gt;关闭&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/Teleport&gt; &lt;/div&gt; &lt;/template&gt; &lt;script setup&gt; import { ref } from &quot;vue&quot;; let isModel = ref(false); &lt;/script&gt; &lt;style&gt; .child { width: 300px; height:300px; background:green; } /**灰色遮罩层 */ .mask-dialog { width: 100%; height:100%; position:absolute; left:0; top:0; background:rgba(0,0,0,0.5) } .box { width: 200px; height:200px; position:absolute; left:50%; top:50%; transform:translate(-50%,-50%); background:pink; text-align:center; } &lt;/style&gt;</pre><div class="contentsignin">Copy after login</div></div>

<Teleport>

Receives a to prop to specify the destination of the transmission. The value of

to

can be a CSS selector string, or id, or it can be a DOM element object. The function of this code is to tell Vue to send the following template fragment to the body tag<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;Teleport to=&quot;#some-id&quot;&gt;html结构代码&lt;/Teleport&gt; &lt;Teleport to=&quot;.some-class&quot;&gt;html结构代码&lt;/Teleport&gt; &lt;Teleport to=&quot;body&quot;&gt;html结构代码&lt;/Teleport&gt; &lt;Teleport to=&quot;html&quot;&gt;html结构代码&lt;/Teleport&gt;</pre><div class="contentsignin">Copy after login</div></div>02-Teleport componentIt isVue is a built-in component officially provided, which can "transfer" a part of the template inside a component to the location of the outer layer of the

DOM

structure of the component. That is, a technology that can move our component

html

structure to a specified location<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;teleport to=&quot;移动到指定的位置,可以是html,body,或id,class&quot;&gt; 里面是Html结构模板内容 &lt;/teleport&gt;</pre><div class="contentsignin">Copy after login</div></div>Note

<Teleport>

When mounting, the transferred to target must already exist in

DOM

. Ideally, this should be an element outside the entire Vue application DOM tree. If the target element is also rendered by Vue, you need to make sure to mount the element before mounting <Teleport> #Place the specified template html at the specified location on the page. It is conditional and cannot be transferred arbitrarily Before installing the component, the target element must exist, that is ,Targets cannot be rendered by the component itself and should ideally ,be located outside the entire

Vue

component tree. The following code will not work<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;template&gt; &lt;div&gt; &lt;Teleport to=&quot;.content&quot;&gt; &lt;div&gt;我是头部的内容&lt;/div&gt; &lt;/Teleport&gt; &lt;/div&gt; &lt;div&gt; 底部内容 &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script setup&gt; &lt;/script&gt; &lt;style&gt; h1 { color: red; } &lt;/style&gt;</pre><div class="contentsignin">Copy after login</div></div>03-What you need to know

teleport just changes the rendered

DOM

structure, It does not affect the logical relationship between components. That is to say, if

<Teleport>

contains a component, then the component always maintains a logical parent-child relationship with the component that uses

. Incoming props and triggered events will also work as usual. <p>这也意味着来自父组件的注入也会按预期工作,子组件将在 <code>Vue Devtools 中嵌套在父级组件下面,而不是放在实际内容移动到的地方

位置移动了,提现在结构模板上,但是数据逻辑依旧存在关联的

04-如何禁用 Teleport

在某些场景下可能需要视情况禁用 <Teleport>。举例来说,我们想要在桌面端将一个组件当做浮层来渲染,但在移动端则当作行内组件。我们可以通过对 <Teleport> 动态地传入一个 disabled prop 来处理这两种不同情况

<Teleport :disabled="isMobile">
  ...
</Teleport>
Copy after login

这里的 isMobile 状态可以根据 CSS media query 的不同结果动态地更新

05-多个 Teleport 共享目标时

一个可重用的模态框组件可能同时存在多个实例。对于此类场景,多个 <Teleport> 组件可以将其内容挂载在同一个目标元素上,而顺序就是简单的顺次追加,后挂载的将排在目标元素下更后面的位置上

比如下面这样的用例

<Teleport to=".content">
  <div>A</div>
</Teleport>
<Teleport to=".content">
  <div>B</div>
</Teleport>
Copy after login

渲染的结果为

<div class="content">
  <div>A</div>
  <div>B</div>
</div>
Copy after login

总结

这个teleport组件在实际开发中还是很实用的,能够解决当组件嵌套层级很深,而后代组件中的模板,想要脱离当前组件结构,解决css布局层面的干扰,那就可以用这个teleport组件

(学习视频分享:vuejs入门教程编程基础视频

The above is the detailed content of An in-depth explanation of how to use the Teleport component in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() =&gt; { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

See all articles