【學習筆記】Vue3之Teleport


Vue3之Teleport

 

原文:https://vue3js.cn/docs/zh/guide/teleport.html#%E4%B8%8E-vue-components-%E4%B8%80%E8%B5%B7%E4%BD%BF%E7%94%A8

 

看一段代碼:

const app = Vue.createApp({}) app.component('modal-button', { template: ` <button @click="modalOpen = true"> Open full screen modal!(With teleport!) </button>

        <teleport to="body">
            <div v-if="modalOpen" class="modal">
                <div> I'm a teleported modal! (My parent is "body") <button @click="modalOpen = false">關閉</button> </div> </div> </teleport> `, data() { return { modalOpen: false } } }) app.mount('#app')

 

與Vue components一起使用

如果<teleport>包含Vue組件,則它仍將是<teleport>父組件的邏輯子組件:

const app = Vue.createApp({ template: ` <h1>Root instance</h1>
        <parent-component />
 ` }) app.component('parent-component', { template: ` <h2>This is a parent component</h2>
        <teleport to="#endofbody">
            <child-component name="John" />
        </teleport>
 ` }) app.component('child-component', { props: ['name'], template: ` <div>Hello, {{ name }}</div>
 ` })

在這種情況下,即使在不同的地方渲染child-component,它仍將是parent-component的子級,並將從中接收name prop

這也意味着來自父組件的注入按預期工作,並且子組件將嵌套在Vue Devtools中的父組件之下,而不是放在實際內容移動到的位置。

 

在同一目標上使用多個teleport

一個常見的用例場景是一個可重用的<Modal>組件,它可能同時有多個實例處於活動狀態。

<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>

 

teleport API

原文:https://vue3js.cn/docs/zh/api/built-in-components.html#teleport

【Props】

to - string,需要prop,必須是有效的查詢選擇器或HTMLElement(如果在瀏覽器環境中使用)。指定將在其中一棟<teleport>內容的目標元素

  <!-- 正確 -->
  <teleport to="#some-id" />
  <teleport to=".some-class" />
  <teleport to="[data-teleport]" />

  <!-- 錯誤 -->
  <teleport to="h1" />
  <teleport to="some-string" />

disabled - boolean. 此可選屬性可用於禁用<teleport>的功能,這意味着其插槽內容將不會移動到任何位置,而是在您在周圍父組件中指定了<teleport>的位置渲染。

<teleport to="#popup" :disabled="displayVideoInline">
    <video src="./my-movie.mp4">
</teleport>

請注意,這將移動實際的DOM節點,而不是被銷毀和重新創建,並且它還將保持任何組件實例的活動狀態。所有有狀態的HTML元素(即播放的視頻)都將保持其狀態。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM