[Easy] Vue3 新特性
1. What are the new features in Vue 3?
Vue 3 有哪些新特性?
Vue 3 引入了許多新特性和改進,主要包括:
主要新特性
- Composition API:新的組件寫法
- Teleport:將組件渲染到 DOM 的其他位置
- Fragment:組件可以有多個根節點
- Suspense:處理非同步組件載入
- 多個 v-model:支援多個 v-model
- 更好的 TypeScript 支援
- 效能優化:更小的打包體積、更快的渲染速度
2. Teleport
Teleport 是什麼?
定義:Teleport 允許我們將組件的內容渲染到 DOM 樹的其他位置,而不改變組件的邏輯結構。
使用場景
常見場景:Modal、Tooltip、Notification 等需要渲染到 body 的組件
點此展開 Teleport 範例
<template>
<div>
<button @click="showModal = true">開啟 Modal</button>
<!-- 使用 Teleport 將 Modal 渲染到 body -->
<Teleport to="body">
<div v-if="showModal" class="modal">
<div class="modal-content">
<h2>Modal 標題</h2>
<p>Modal 內容</p>
<button @click="showModal = false">關閉</button>
</div>
</div>
</Teleport>
</div>
</template>
<script setup>
import { ref } from 'vue';
const showModal = ref(false);
</script>
優勢
- 解決 z-index 問題:Modal 渲染到 body,不受父組件樣式影響
- 保持邏輯結構:組件邏輯仍在原位置,只是 DOM 位置不同