Vue3内置组件补充Teleport

52 篇文章 2 订阅

在组件化开发中,我们封装一个组件A,在另一个组件B中使用:

  • 那么组件A中template的元素,会被挂载到组件B中template的某个位置;
  • 最终我们的应用程序会形成一颗Dom树结构;

但是某些情况下,我们希望组件不是挂载在这个组件树上的,可能是移动到Vue app之外的其他位置:

  • 比如移动到body元素上,或者我们有其他的div#app之外的元素上:
  • 这个时候我们就可以通过teleport来完成;

Teleport是什么呢?

  • 它是一个Vue提供的内置组件,类似于react的Portals;

  • teleport翻译过来是心灵传输、远距离运输的意思;

    它有两个属性:

      1. to
      >  to:指定将其中的内容移动到的目标元素,可以使用选择器;
      2. disabled
      >   disabled:是否禁用 teleport 的功能;
    

示例代码

// index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
    <style>
      #abc{
        border: 1px solid orange;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <div id="abc"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

// App.vue

<template>
  <div class="app">
    <suspense>
      <template #default>
        <async-home></async-home>
      </template>
      <template #fallback>
        <h2>Loading</h2>
      </template>
    </suspense>  
  </div>
</template>  
<script setup>
import { defineAsyncComponent } from 'vue';

const AsyncHome = defineAsyncComponent(() => import("./AsyncHome.vue"))

</script>

<style scoped>

</style>

感谢大家观看,我们下次再见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

2019ab

你的鼓励就是我的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值