Vue3.0(2):Teleport

本文介绍了Vue.js中Teleport组件的功能与用法,通过对比使用前后的代码示例,展示了如何利用Teleport将DOM元素渲染到页面上的任意位置,同时保持组件之间的父子关系不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Teleport

官方文档

Teleport汉语意思是传送,从官方文档看这个名字很符合,可以将代码片段传送到其他位置

官方示例1(略作修改)

//不使用Teleport
<template>
  <div>
    <el-button type="primary" @click="openModel = true">打开</el-button>
    <div title="main">
      <div >
        <div
          v-show="openModel"
          style="width: 100px; height: 100px; background: red"
        >
          <el-button type="primary" @click="openModel = false">关闭</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

//使用Teleport
<template>
  <div>
    <el-button type="primary" @click="openModel = true">打开</el-button>
    <div title="main">
        <teleport to="body">
        <div
          v-show="openModel"
          style="width: 100px; height: 100px; background: red"
        >
          <el-button type="primary" @click="openModel = false">关闭</el-button>
        </div>
      </teleport>
      </div>
    </div>
  </div>
</template>

在这里插入图片描述
在这里插入图片描述

  • 首先用了v-show代替了v-if,原因就不解释了
  • 从上面两张图可以看出不使用teleport元素是被渲染到了div中,而使用teleport元素直接被渲染到了body下

与 Vue components 一起使用

<teleport to="#tobody">
    <modal-button></modal-button>
 </teleport>
  • 即使在不同的地方渲染子组件,它仍将是 父组件 的子级,并将从中接收 父组件传递的prop属性。
  • #tobody 是元素的id标识

在同一目标上使用多个 teleport

<teleport to="#modals">
  <div>A</div>
</teleport>
<teleport to="#modals">
  <div>B</div>
</teleport>

<!-- result-->
<div id="modals">
  <div>A</div>
  <div>B</div>
</div>
  • 多个 组件可以将其内容挂载到同一个目标元素。顺序将是一个简单的追加——稍后挂载将位于目标元素中较早的挂载之后。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无知的小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值