> 在vue3中可以通過`teleport`這個內置組件將我們封裝的組件渲染到指定的元素中,比如渲染到`body`中,這非常適用于一些彈窗組件。
使用`<teleport>`,告訴 Vue “將這個 HTML**傳送**到‘**body**’標簽下”。
~~~
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">
Close
</button>
</div>
</div>
</teleport>
`,
data() {
return {
modalOpen: false
}
}
})
~~~
一旦我們單擊按鈕打開模態框,Vue 將正確地將模態框內容渲染為`body`標簽的子級。