vue.joedoe.dev

← Todas las recetasLo que trae Vue

Modal con Teleport y <dialog>

Teleport lo saca a <body> y el <dialog> nativo pone el foco, el Esc y el fondo. Con SSR (Nuxt, Astro), teletranspórtalo solo tras montar: hidratar un Teleport a <body> puede romper la página entera, me pasó haciendo esta.

Vue SFC
<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>

Esta caja tiene overflow: hidden, y aun así el modal sale entero.

↑↓ moverse · ↵ abrir · esc cerrar