在 Vue 中,元件會隨著父元件渲染在 DOM 裡,但像 Modal、Notification 等等這類 UI,通常需要顯示在最上層,避免被父層的 CSS overflow:hidden 或 z-index 擋住
這時候就可以用 Vue 的內建功能 <teleport>
,把元件內容渲染到指定的 DOM 節點
<template>
<div>
<h2>主頁面</h2>
<button @click="show = true">開啟 Modal</button>
<teleport to="body">
<div v-if="show" class="modal-overlay">
<div class="modal-content">
<h3>我是 Modal 🎉</h3>
<button @click="show = false">關閉</button>
</div>
</div>
</teleport>
</div>
</template>
<script setup>
import { ref } from 'vue'
const show = ref(false)
</script>
Vue 會自動把裡面的 DOM 內容傳送到 <body>
,而不是跟在父元件的 <div>
下面
<teleport to="body"> ... </teleport>