<script setup lang="ts">
import { onMounted, ref, useTemplateRef, watch } from "vue";
/*
* A native <dialog> moved to <body> with Teleport, so no parent's overflow
* or z-index can trap it. showModal() brings focus trapping, Esc and the
* backdrop for free.
*
* With server rendering (Nuxt, Astro…), teleport only after mounting: the
* server's HTML has nothing in <body> to match, and hydrating a Teleport
* there can wreck the page.
*/
const open = defineModel<boolean>({ default: false });
const { title } = defineProps<{ title: string }>();
const dialog = useTemplateRef<HTMLDialogElement>("dialog");
const mounted = ref(false);
onMounted(() => (mounted.value = true));
watch(open, (value) => {
if (value) dialog.value?.showModal();
else dialog.value?.close();
});
</script>
<template>
<Teleport v-if="mounted" to="body">
<dialog ref="dialog" class="modal" @close="open = false" @click.self="open = false">
<h2>{{ title }}</h2>
<slot />
<form method="dialog"><button>Cerrar</button></form>
</dialog>
</Teleport>
</template>
<style scoped>
.modal {
max-width: min(90vw, 26rem);
padding: 1.25rem 1.5rem;
border: 0;
border-radius: 14px;
box-shadow: 0 20px 50px rgb(0 0 0 / 0.3);
}
.modal::backdrop {
background: rgb(16 38 27 / 0.45);
}
.modal h2 {
margin-top: 0;
}
</style><script setup lang="ts">
import { ref } from "vue";
import Modal from "./Modal.vue";
const open = ref(false);
</script>
<template>
<div class="trap">
<p class="muted">Esta caja tiene overflow: hidden, y aun así el modal sale entero.</p>
<button @click="open = true">Abrir el modal</button>
</div>
<Modal v-model="open" title="Hola 👋">
<p>Pulsa Esc, haz clic fuera o usa el botón.</p>
</Modal>
</template>
<style scoped>
.trap {
overflow: hidden;
max-height: 7rem;
padding: 0.75rem;
border: 2px dashed #42b883;
border-radius: 10px;
}
</style>Esta caja tiene overflow: hidden, y aun así el modal sale entero.