程序员鸡皮

文章 分类 评论
95 3 22

站点介绍

一名PHP全栈程序员的日常......

Vue3内置组件补充Teleport

abzzp 2024-08-31 682 0条评论 前端 vue

首页 / 正文
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......

发布于2024-07-04

在组件化开发中,我们封装一个组件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>

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

评论(0)

最新评论

  • fintechbase

    It's not my first time to pay a visit this web page, i am visiting this website dailly and get good facts from here every day.

  • fintechbase

    Hello, i think that i saw you visited my site so i got here to go back the want?.I'm trying to find things to improve my web site!I suppose its adequate to use a few of your concepts!!

  • fintechbase

    Touche. Outstanding arguments. Keep up the great effort.

  • fintechbase

    Wow, this post is good, my younger sister is analyzing these things, therefore I am going to let know her.

  • digital banking

    There's certainly a lot to learn about this topic. I like all the points you've made.

  • 觀景碼頭

    所有文章都令人印象深刻。由衷感谢 带来的灵感。

  • 圣巴托罗梅奥

    你 百分百 分享经验。坚持!

  • 孤懸外海

    不常看到, 这么高质量的内容。谢谢。

  • abzzp

    @十二使徒岩 哪张图片?

  • 十二使徒岩

    照片令人惊艳。继续保持 心情。

日历

2026年01月

    123
45678910
11121314151617
18192021222324
25262728293031

文章目录

站点公告
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......
点击小铃铛关闭
配色方案