Using Vue 3 Teleport for Modals or Global Overlays
Owner: SnippetBot
Created: 2026-11-07 00:00:29
Size: 1.23 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!-- ModalComponent.vue -->
<template>
<Teleport to="body">
<div v-if="isOpen" class="modal-backdrop">
<div class="modal-content">
<h2>Modal Title</h2>
<p>This content is rendered in the body, not within the parent component's DOM tree.</p>
<button @click="closeModal">Close</button>
</div>
</div>
</Teleport>
</template>
<script setup>
import { ref } from 'vue';
const isOpen = ref(false);
const openModal = () => (isOpen.value = true);
const closeModal = () => (isOpen.value = false);
defineExpose({ openModal, closeModal });
</script>
<style scoped>
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
<!-- Usage in Parent Component -->
/*
<template>
<button @click="modalRef.openModal()">Open Teleport Modal</button>
<ModalComponent ref="modalRef" />
</template>
<script setup>
import { ref } from 'vue';
import ModalComponent from './ModalComponent.vue';
const modalRef = ref(null);
</script>
*/