vue3內(nèi)置組件之Teleport(傳送門)

在一些場景中,比如使用modal時,我們想要將modal放在具體的vue頁面中,功能與位置保持一致。但是在展示時,又希望直接將它放在body下,方便實現(xiàn)定位樣式。面對功能位置與樣式位置的不統(tǒng)一,vue3中提供一對<teleport ></teleport>標簽用于移動dom的位置到指定元素。
modal組件:

<template>
  <div class='modal'>
    <p>這是一個模態(tài)框</p>
    <button>關(guān)閉</button>
  </div>
</template>

<script>
export default {
  name: 'modal',
};
</script>

<style lang='scss' scoped>
  .modal{
    position: absolute;
    left: 40%;
    top: 40%;
    width: 100px;
    height: 100px;
    border: 1px skyblue solid;
  }
</style>

父組件:

<template>
  <div class='test'>
    <p>這是父頁面</p>
    <modal/>
  </div>
</template>

<script>
import modal from './modal';
import { defineComponent, ref} from 'vue';

export default defineComponent({
  name: 'test',
  components: {
    modal
  },
});
</script>

<style lang='scss' scoped>
  .test {
    position: absolute;
    left: 100px;
    top: 100px;
    width: 200px;
    border: 1px solid #000;
    color: #00EAFF;
  }
</style>

此時dom結(jié)構(gòu)為:


image.png

如果我們嵌套teleport標簽,標簽上的to參數(shù)表示要將包裹的內(nèi)容所移動到的父級元素。父組件變?yōu)椋?/p>

<template>
  <div class='test'>
    <p>這是父頁面</p>
    <teleport to='body'>
      <modal/>
    </teleport>
  </div>
</template>

dom結(jié)構(gòu)變?yōu)椋?/p>

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

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