Modal
Display a dialog above the page for editing, confirmation or focused content. Use v-model:visible for a dialog declared in a template, or HuiModal.open() for an independent dialog opened from code.
Import
import { HuiModal, useModalContext } from '@nscode/handy-ui'
import type { ModalProps, ModalCloseTrigger, ModalHandle, ModalResult } from '@nscode/handy-ui'
Examples
Basic dialog and slots
The default slot is the body. Use header to replace the title and footer to supply actions. Closing updates v-model:visible; content remains mounted after the first opening unless destroyOnClose is enabled.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiModal, HuiSpace } from '@nscode/handy-ui'
const visible = ref(false)
const value = ref('')
</script>
<template>
<HuiButton @click="visible = true">Open dialog</HuiButton>
<HuiModal v-model:visible="visible" title="Edit details" :width="440">
<HuiInput v-model="value" placeholder="Values remain after closing" />
<template #footer
><HuiSpace><HuiButton @click="visible = false">Close</HuiButton></HuiSpace></template
>
</HuiModal>
</template>
Built-in footer and asynchronous confirmation
Set showFooter to display Cancel and Confirm. A beforeConfirm result of false, a thrown error or a rejected Promise keeps the dialog open. Pending confirmation displays loading and blocks competing operations. User cancellation and closing use beforeClose instead.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiModal, HuiSpace } from '@nscode/handy-ui'
import type { ModalCloseTrigger } from '@nscode/handy-ui'
const visible = ref(false)
const name = ref('')
const state = ref('Not saved')
const save = async () => {
if (!name.value.trim()) {
state.value = 'Enter a name first'
return false
}
await new Promise((resolve) => setTimeout(resolve, 500))
state.value = `Saved ${name.value}`
}
const closed = (trigger?: ModalCloseTrigger | 'confirm') => {
state.value += `; closed by ${trigger ?? 'external state'}`
}
</script>
<template>
<HuiSpace direction="vertical" align="start"
><HuiButton @click="visible = true">Edit and save</HuiButton><span>{{ state }}</span></HuiSpace
>
<HuiModal
v-model:visible="visible"
title="Save details"
show-footer
:before-confirm="save"
@close="closed"
>
<HuiInput v-model="name" placeholder="Name" />
</HuiModal>
</template>
Closing controls
beforeClose receives one reason: close-button, mask, escape or cancel. Only false, a thrown error or a rejected Promise blocks closing; undefined also allows closing. Return a Promise to wait for asynchronous work. A direct parent change to v-model:visible bypasses this guard and emits close without a reason.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiModal, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { ModalCloseTrigger } from '@nscode/handy-ui'
const visible = ref(false)
const allowed = ref(false)
const reason = ref('No close attempt')
const beforeClose = (trigger: ModalCloseTrigger) => {
reason.value = trigger
return allowed.value
}
</script>
<template>
<HuiSpace direction="vertical" align="start"
><HuiButton @click="visible = true">Open guarded dialog</HuiButton
><span>{{ reason }}</span></HuiSpace
>
<HuiModal v-model:visible="visible" title="Close guard" show-footer :before-close="beforeClose">
<HuiSpace align="center"><HuiSwitch v-model="allowed" /><span>Allow closing</span></HuiSpace>
</HuiModal>
</template>
Size, centering, fullscreen and dragging
Numbers in width and top use px. center vertically centers the panel; fullscreen fills the viewport. With draggable, drag the title area using a mouse, touch or pen. Esc during a drag restores its starting position without closing the dialog. Pointer capture starts after moving 3px, so pressing and releasing a title-slot help icon still delivers its click.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiModal, HuiSpace, HuiIcon, HuiMessage } from '@nscode/handy-ui'
const centered = ref(false)
const fullscreen = ref(false)
const draggable = ref(false)
const showHelp = () =>
HuiMessage.info('Drag the title to move; Escape restores the starting position.')
</script>
<template>
<HuiSpace wrap
><HuiButton @click="centered = true">Centered 420px</HuiButton
><HuiButton @click="fullscreen = true">Fullscreen</HuiButton
><HuiButton @click="draggable = true">Draggable</HuiButton></HuiSpace
>
<HuiModal v-model:visible="centered" title="Centered" center :width="420"
><p>Centered in the viewport.</p></HuiModal
>
<HuiModal v-model:visible="fullscreen" title="Fullscreen" fullscreen
><p>Only the content area scrolls.</p></HuiModal
>
<HuiModal v-model:visible="draggable" title="Drag this title" draggable :width="420" top="12vh">
<template #header
><HuiSpace
><span>Drag this title</span
><HuiIcon
name="help"
role="button"
tabindex="0"
aria-label="Dragging help"
style="cursor: pointer"
@click="showHelp"
@keydown.enter.prevent="showHelp"
@keydown.space.prevent="showHelp" /></HuiSpace
></template>
<p>Closing and reopening restores the default position.</p>
</HuiModal>
</template>
Opening order and nested overlays
Within the same mount target and stacking level, each opening moves the existing root to the end of the target. The most recently opened Modal or Drawer therefore appears on top, including a dialog that was opened and closed earlier. Content state is preserved. Different targets or explicit z-index overrides still follow CSS stacking contexts.
Dropdowns, popovers and tooltips inside the dialog also move their teleported roots to the end of their targets when opened. Reopening one after closing and reopening the dialog therefore keeps it above the dialog. In-place popups, such as Popover teleport=false, stay in their original positions and follow their container's stacking and clipping rules.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiModal, HuiSpace } from '@nscode/handy-ui'
const first = ref(false)
const second = ref(false)
const text = ref('')
</script>
<template>
<HuiSpace wrap
><HuiButton @click="second = true">Open B alone first</HuiButton
><HuiButton @click="first = true">Open A</HuiButton></HuiSpace
>
<HuiModal v-model:visible="first" title="A" :width="520"
><HuiButton @click="second = true">Open B above A</HuiButton></HuiModal
>
<HuiModal v-model:visible="second" title="B" :width="360" top="25vh"
><HuiInput v-model="text" placeholder="This value is kept on reopen"
/></HuiModal>
</template>
Esc and Tab focus trapping apply to the most recently opened overlay. Body scrolling is restored after every overlay using the scroll lock has closed.
Mount targets and legacy in-place rendering
The default target is body, avoiding ancestor transform, filter and overflow restrictions. appendTo accepts a selector or a connected HTMLElement. The target is resolved on every opening and when it changes. A missing target, invalid selector or disconnected element falls back to body with a development warning, and closing/unmounting still cleans up normally.
An initially open dialog waits for the template's other nodes to mount before resolving a target that was not yet available. The target may appear after the dialog in the same template. Moving between valid targets retains the existing content instance.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiModal, HuiSpace } from '@nscode/handy-ui'
const custom = ref(false)
const inline = ref(false)
</script>
<template>
<HuiSpace wrap
><HuiButton @click="custom = true">Custom target</HuiButton
><HuiButton @click="inline = true">Legacy in-place</HuiButton></HuiSpace
>
<HuiModal v-model:visible="custom" append-to="#modal-en-target" title="Custom target"
><p>The node is mounted in the target below.</p></HuiModal
>
<div id="modal-en-target" style="min-height: 80px; border: 1px dashed var(--hui-border-color)">
Mount target
</div>
<HuiModal v-model:visible="inline" :append-to-body="false" title="In-place"
><p>This root stays at its template position.</p></HuiModal
>
</template>
The deprecated appendToBody is retained for one version: explicit false keeps in-place rendering; true uses body. appendTo takes priority when both are supplied. Omit appendTo when relying on the legacy in-place mode.
Moving the root to body changes DOM ancestry. Ancestor selectors, a parent's scoped :deep() rules, CSS variables overridden on ancestors, and local data-palette containers no longer reach the moved root through that former ancestry. Native form fields moved out of a <form> also lose that automatic form association. To preserve these relationships temporarily, omit appendTo and use :append-to-body="false", or explicitly mount into the relevant container. Vue provide/inject, slots and component events keep their component relationships.
Open from code
HuiModal.open() returns a handle with result, close() and update(). The Promise resolves after closing and container cleanup, with action equal to confirm, cancel or close; ordinary cancellation does not reject. The built-in footer is enabled by default for this entry point.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiModal, HuiSpace } from '@nscode/handy-ui'
const state = ref('No result yet')
const open = async () => {
const handle = HuiModal.open<string>({
title: 'Save from code',
content: 'Confirm to save.',
width: 420,
onConfirm: () => 'saved'
})
const result = await handle.result
state.value = `${result.action}: ${result.data ?? ''}`
}
</script>
<template>
<HuiSpace direction="vertical" align="start"
><HuiButton @click="open">Open from code</HuiButton><span>{{ state }}</span></HuiSpace
>
</template>
Pass component and optional props for complex content. Inside that component's setup, useModalContext<R>() supplies onConfirm, confirm(data), cancel(), close(), setConfirmLoading() and update(). A registered content confirmation handler takes priority over the options handler. Outside a function-created dialog, the composable returns undefined.
Teleported content and returning focus
Popups teleported from a dialog remain in its Tab scope. A dialog opened from a menu item returns to the menu trigger after the item becomes hidden.
<script setup lang="ts">
import { h, ref } from 'vue'
import {
HuiButton,
HuiDropdown,
HuiDropdownItem,
HuiDropdownMenu,
HuiModal,
HuiPopover,
HuiSpace
} from '@nscode/handy-ui'
const visible = ref(false)
const edit = () =>
HuiModal.open({
title: 'Edit name',
content: () => h('input', { 'aria-label': 'Name', autofocus: true })
})
</script>
<template>
<HuiSpace>
<HuiButton @click="visible = true">Check Tab through teleported content</HuiButton>
<HuiDropdown trigger="click" @command="edit">
<HuiButton>Menu trigger</HuiButton>
<template #dropdown
><HuiDropdownMenu
><HuiDropdownItem command="edit">Edit name</HuiDropdownItem></HuiDropdownMenu
></template
>
</HuiDropdown>
</HuiSpace>
<HuiModal v-model:visible="visible" title="Focus scope">
<HuiSpace>
<HuiButton>Dialog button</HuiButton>
<HuiPopover title="Teleported to body"
><HuiButton>Open popover</HuiButton
><template #content><HuiButton>Popover button</HuiButton></template></HuiPopover
>
</HuiSpace>
</HuiModal>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| visible | boolean | false | Open state, supports v-model:visible |
| title | string | '' | Title when no header slot is supplied |
| width | number | string | '50%' | Panel width; numbers use px |
| top | number | string | '15vh' | Distance from the top; numbers use px |
| center | boolean | false | Vertical centering |
| fullscreen | boolean | false | Fill the viewport |
| draggable | boolean | false | Drag by the title; disabled in fullscreen |
| modal | boolean | true | Display a mask and trap focus |
| appendTo | string | HTMLElement | 'body' | Resolved target; invalid targets fall back to body |
| appendToBody | boolean | — | Deprecated; false preserves in-place rendering, appendTo takes priority |
| lockScroll | boolean | Follows modal | Lock body scrolling while open |
| closeOnClickModal | boolean | true | Close when clicking the mask |
| closeOnPressEscape | boolean | true | Close the top overlay with Esc |
| showClose | boolean | true | Display the close button |
| beforeClose | (trigger) => boolean | void | Promise<boolean | void> | — | Guard user-initiated closing |
| showFooter | boolean | false | Show built-in actions when footer slot is absent |
| confirmButtonText / cancelButtonText | string | Locale | Visible action text; empty strings are preserved |
| confirmButtonType | ButtonType | 'primary' | Confirm button type |
| showConfirmButton / showCancelButton | boolean | true | Display the corresponding action |
| confirmButtonLoading | boolean | false | Controlled confirmation loading |
| beforeConfirm | () => boolean | void | Promise<boolean | void> | — | Guard built-in confirmation |
| destroyOnClose | boolean | false | Destroy content after the leave animation |
Events
| Event | Parameters | Description |
|---|---|---|
| update:visible | boolean | Request changing the open state |
| open / opened | — | Opening starts / enter animation finishes |
| close | trigger?: ModalCloseTrigger | 'confirm' | Closing starts; external changes have no trigger |
| closed | — | Leave finishes; also completes a close before delayed initial mounting |
| confirm | — | Confirmation passed, before requesting close |
| cancel | — | Built-in Cancel clicked, before its close guard |
Slots
| Slot | Scope | Description |
|---|---|---|
| default | — | Dialog body |
| header | — | Replace title content |
| footer | { confirm, cancel, confirmLoading } | Replace built-in actions while retaining their flows |
Methods
Template dialogs use v-model:visible. The component has no instance open/close methods.
| Function | Description |
|---|---|
| HuiModal.open(options) | Create a function-based dialog and return ModalHandle |
| HuiModal.closeAll() | Close all dialogs created by open; bypass close guards |
| useModalContext() | Access the current function dialog from its content setup |
ModalOpenOptions accepts component/content, content props, title, width, top, center, fullscreen, draggable, modal, appendTo, lockScroll, close controls, built-in footer settings, onConfirm, beforeClose, onOpened, onClosed and appContext. component takes priority over content. handle.update() changes options while open. Missing mount targets follow the same safe body fallback as template dialogs.
Types
type ModalCloseTrigger = 'close-button' | 'mask' | 'escape' | 'cancel'
type ModalAction = 'confirm' | 'cancel' | 'close'
interface ModalResult<R = unknown> {
action: ModalAction
data?: R
}
interface ModalHandle<R = unknown> {
readonly id: string
readonly result: Promise<ModalResult<R>>
close: () => void
update: (options: Partial<ModalOpenOptions<R>>) => void
}