iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
Vue.js

Vue 新手學習紀錄系列 第 18

Day 18 | Teleport: 讓 Modal 浮在最上層

  • 分享至 

  • xImage
  •  

為什麼需要 Teleport?

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

適合用 Teleport 的情境

  • Modal / Dialog
  • Toast / Notification
  • Tooltip
  • 下拉選單

上一篇
Day 17 | Vue 部署到 Github Pages 上
下一篇
Day 19:跨元件資料傳遞 Provide/Inject
系列文
Vue 新手學習紀錄22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言