javascript / intermediate
Snippet
Decoupling Modals with the Teleport Component
Teleport allows you to render a part of a component's template at a different location in the DOM tree (e.g., the body), while still maintaining the logic and state within the original component. This is essential for z-index management in CSS.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template><div class="container"><button @click="isOpen = true">Open Modal</button><Teleport to="body"><div v-if="isOpen" class="modal-overlay"><div class="modal-content"><p>I am rendered outside the container!</p><button @click="isOpen = false">Close</button></div></div></Teleport></div></template><script setup>import { ref } from 'vue';const isOpen = ref(false);</script>
vue
Breakdown
1
<Teleport to="body">
Targets the end of the <body> tag as the render destination.
2
v-if="isOpen"
Controls the visibility of the teleported content based on component state.