32.teleport內(nèi)置組件

認(rèn)識(shí)teleport內(nèi)置組件

在組件化開(kāi)發(fā)中,我們封裝一個(gè)組件A,在另外一個(gè)組件B中使用:

  • 那么組件A中template的元素,會(huì)被掛載到組件B中template的某個(gè)位置;
  • 最終我們的應(yīng)用程序會(huì)形成一顆DOM樹(shù)結(jié)構(gòu);
但是某些情況下,我們希望組件不是掛載在這個(gè)組件樹(shù)上的,可能是移動(dòng)到Vue app之外的其他位置: + 比如移動(dòng)到body元素上,或者我們有其他的div#app之外的元素上;
  • 這個(gè)時(shí)候我們就可以通過(guò)teleport來(lái)完成;
Teleport是什么呢?
  • 它是一個(gè)Vue提供的內(nèi)置組件,類(lèi)似于react的Portals;
  • teleport翻譯過(guò)來(lái)是心靈傳輸、遠(yuǎn)距離運(yùn)輸?shù)囊馑迹?
    它有兩個(gè)屬性:
    • to:指定將其中的內(nèi)容移動(dòng)到的目標(biāo)元素,可以使用選擇器;
    • disabled:是否禁用 teleport 的功能;

public/index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    
     <!-- teleport目標(biāo)位置 -->
    <div id="why"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

App.vue

<template>
  <div>
    <teleport to="#why">
      <h1>今天天氣不錯(cuò)</h1>
      <!--如果teleport內(nèi)部有組件,組件的內(nèi)容也會(huì)一同掛載到目標(biāo)DOM內(nèi)部-->
      <hello-world />
    </teleport>
    <!--如果使用過(guò)個(gè)teleport掛載到同一目標(biāo)Dom內(nèi),會(huì)一次按照屬性進(jìn)行掛載-->
    <teleport to="#why">
      <button>按鈕</button>
    </teleport>
  </div>
</template>

<script>
  import HelloWorld from './HelloWorld.vue'
  export default {
    components: {
      HelloWorld
    }
  }
</script>

<style lang="scss" scoped>

</style>

HelloWorld.vue

<template>
  <div>
    hello world
  </div>
</template>

<script>
  export default {
    
  }
</script>

<style lang="scss" scoped>

</style>
image.png

此文檔主要內(nèi)容來(lái)源于王紅元老師的vue3+ts視頻教程

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容