MessageBox
Provides dialogs resembling the system alert, confirm and prompt. A small dialog with an overlay appears in the center of the window to show information, confirm an operation or request one input value. Use the function API, which returns a Promise.
Import
import { HuiMessageBox } from '@nscode/handy-ui'
Basic Usage
HuiMessageBox.alert(message, title) opens an alert with only a Confirm button. Confirm resolves the Promise; the top-right close button rejects with 'close', so handle catch as well. Esc and overlay clicks are ignored by default. Explicitly enable closeOnPressEscape or closeOnClickModal to close through those actions, also rejecting with 'close'.
Calling HuiMessageBox(message, title, options) directly has the same defaults as alert, with only a Confirm button.
<script setup lang="ts">
import { HuiButton, HuiMessage, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const open = () => {
HuiMessageBox.alert('This is an informational message', 'Notice', {
confirmButtonText: 'Got it'
})
.then(() => HuiMessage.success('Confirm clicked'))
.catch((action) => HuiMessage.info(`Closed: ${action}`))
}
const openDirect = () => {
HuiMessageBox('A direct HuiMessageBox call shows only Confirm by default', 'Notice').catch(
() => {}
)
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open">Show alert (alert)</HuiButton>
<HuiButton @click="openDirect">Call HuiMessageBox() directly</HuiButton>
</HuiSpace>
</template>
Confirmation
HuiMessageBox.confirm includes a Cancel button by default. Confirm resolves; Cancel rejects with 'cancel'; the close button, Esc and overlay clicks reject with 'close'. Inspect the rejection value when these actions need different handling.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox } from '@nscode/handy-ui'
const result = ref('')
const remove = async () => {
try {
await HuiMessageBox.confirm('Delete this record?', 'Confirm deletion', {
confirmButtonText: 'Delete',
confirmButtonType: 'danger',
type: 'warning'
})
} catch (action) {
// action is 'cancel' or 'close'
result.value = `Not deleted; rejected with '${action}'`
return
}
result.value = 'Deleted'
}
</script>
<template>
<HuiButton type="danger" @click="remove">Delete</HuiButton>
<p style="margin-top: 12px">
{{ result || 'Open the dialog, then try Delete, Cancel and × separately' }}
</p>
</template>
Input Prompt
HuiMessageBox.prompt shows an input below the content and includes a Cancel button by default. Its placeholder comes from the active locale. The input receives focus on open, and Enter in the input acts as Confirm. Confirmation returns MessageBoxPromptData with action: 'confirm' and an always-string value. Empty input returns ''.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const name = ref('')
const rename = async (placeholder?: string) => {
try {
const { value } = await HuiMessageBox.prompt('Enter a new name', 'Rename', {
inputPlaceholder: placeholder
})
name.value = value
} catch {
// Do not change the name on cancellation or closing
}
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="rename('Up to 20 characters')">Rename (custom placeholder)</HuiButton>
<HuiButton @click="rename()">Rename (default placeholder)</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">Current name: {{ name || 'Untitled' }}</p>
</template>
Initial Input Values
inputValue is read once when this dialog is created. It is not a controlled value: changing the supplied configuration after opening does not replace the draft. Each call reads its own initial value, and an explicit '' opens with an empty input.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const name = ref('Existing name')
const rename = async (empty = false) => {
try {
const { value } = await HuiMessageBox.prompt('Enter a name', 'Rename', {
inputValue: empty ? '' : name.value
})
name.value = value
} catch {
// Cancellation keeps the current value.
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="rename()">Open with the current name</HuiButton>
<HuiButton @click="rename(true)">Open with an empty string</HuiButton>
</HuiSpace>
<span>Saved name: {{ name || 'Untitled' }}</span>
</HuiSpace>
</template>
Input Types
inputType supports text, password, number, and textarea. Numeric input also returns a string. In multiline input, Enter inserts a new line; Ctrl+Enter or Cmd+Enter confirms. Enter during IME composition does not confirm.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxInputType, MessageBoxPromptData } from '@nscode/handy-ui'
const result = ref('No input saved')
const open = async (inputType: MessageBoxInputType) => {
try {
const data: MessageBoxPromptData = await HuiMessageBox.prompt(
'Edit and confirm',
'Input type',
{
inputType,
inputValue:
inputType === 'number'
? '123'
: inputType === 'textarea'
? 'First line\nSecond line'
: 'Existing content'
}
)
result.value = `${data.action}: ${JSON.stringify(data.value)}; type: ${typeof data.value}`
} catch (action) {
result.value = `Not saved: ${action}`
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="open('text')">text</HuiButton>
<HuiButton @click="open('password')">password</HuiButton>
<HuiButton @click="open('number')">number</HuiButton>
<HuiButton @click="open('textarea')">textarea</HuiButton>
</HuiSpace>
<span>Multiline: Enter adds a line; Ctrl/Cmd+Enter confirms.</span>
<span role="status">{{ result }}</span>
</HuiSpace>
</template>
Panel Width and Styling
width, class, and style apply to this call's actual .hui-message-box__container panel. Numeric widths use pixels; CSS widths are also accepted. The default maximum width is 90vw, so the panel shrinks on narrow screens. A matching style property takes precedence over width. Other calls do not inherit these styles. Use a global selector to target a panel teleported to body from a scoped stylesheet.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const result = ref('Not opened')
const open = async (width: string | number) => {
try {
await HuiMessageBox.confirm(
'The panel fits narrow screens; the overlay still covers the page.',
'Panel style',
{
width,
class: ['message-box-demo-panel'],
style: { borderRadius: 'var(--hui-border-radius-xl)', padding: 'var(--hui-spacing-6)' }
}
)
result.value = 'Confirmed'
} catch (action) {
result.value = `Not confirmed: ${action}`
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="open(520)">width: 520</HuiButton>
<HuiButton @click="open('40rem')">width: 40rem</HuiButton>
</HuiSpace>
<span role="status">{{ result }}</span>
</HuiSpace>
</template>
Input Validation
On confirmation, input is checked in this order. A failure displays an error below the input and keeps the dialog open:
inputPattern: a nonmatching regular expression displaysinputErrorMessage.inputValidator: returningfalsedisplaysinputErrorMessage; returning a string displays that string as the error; returningtruepasses validation.
inputErrorMessage defaults to the localized invalid-input message. An empty string also falls back to that default. Error strings returned by inputValidator are preserved exactly and do not change with the locale.
Configuring any of inputPlaceholder, inputPattern or inputValidator also makes alert and confirm display an input.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxData } from '@nscode/handy-ui'
const result = ref('')
const handle = (promise: Promise<MessageBoxData>) => {
promise
.then(({ value }) => {
result.value = `Entered: ${value}`
})
.catch(() => {})
}
const byPattern = () => {
handle(
HuiMessageBox.prompt('Enter an email address', 'Notice', {
inputPattern: /^[^@\s]+@[^@\s]+\.[^@\s]+$/,
inputErrorMessage: 'Invalid email address'
})
)
}
const byMessage = () => {
handle(
HuiMessageBox.prompt('Set a password', 'Notice', {
inputValidator: (value) => value.length >= 6 || 'At least 6 characters'
})
)
}
const byFalse = () => {
handle(
HuiMessageBox.prompt('Enter a quantity', 'Notice', {
inputValidator: (value) => /^\d+$/.test(value)
})
)
}
const alertWithInput = () => {
handle(
HuiMessageBox.alert('Setting inputPlaceholder also gives alert an input', 'Notice', {
inputPlaceholder: 'Enter any text'
})
)
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="byPattern">Regular expression (inputPattern)</HuiButton>
<HuiButton @click="byMessage">Validator returns a string</HuiButton>
<HuiButton @click="byFalse">Validator returns false</HuiButton>
<HuiButton @click="alertWithInput">Alert with an input</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">
{{ result || 'Confirm invalid input to see the validation message' }}
</p>
</template>
Message Types
type accepts success, warning, info or error to show a correspondingly colored icon before the title. Omitting it shows no icon.
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxMessageType } from '@nscode/handy-ui'
const show = (type?: MessageBoxMessageType) => {
HuiMessageBox.alert(`type is ${type ?? 'Omitted'}`, type ?? 'No icon', { type }).catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton type="success" @click="show('success')">Success (success)</HuiButton>
<HuiButton type="warning" @click="show('warning')">Warning (warning)</HuiButton>
<HuiButton type="info" @click="show('info')">Information (info)</HuiButton>
<HuiButton type="danger" @click="show('error')">Error (error)</HuiButton>
<HuiButton @click="show()">Omit type</HuiButton>
</HuiSpace>
</template>
Buttons
confirmButtonTextandcancelButtonTextchange the labels, which default to the active locale's Confirm and Cancel. An explicit empty string is preserved without fallback.confirmButtonTypeandcancelButtonTypeacceptprimary,success,warning,danger,infoordefault. The Confirm button defaults toprimary; Cancel defaults todefault.showConfirmButtonandshowCancelButtoncontrol which buttons are shown.
Each button in the first row opens a dialog with a different Confirm button type:
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxOptions } from '@nscode/handy-ui'
type ButtonType = NonNullable<MessageBoxOptions['confirmButtonType']>
const types: ButtonType[] = ['primary', 'success', 'warning', 'danger', 'info', 'default']
const open = (message: string, options: MessageBoxOptions) => {
HuiMessageBox.confirm(message, 'Notice', options).catch(() => {})
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">Confirm button</span>
<HuiButton
v-for="type in types"
:key="type"
:type="type"
@click="open(`confirmButtonType is ${type}`, { confirmButtonType: type })"
>
{{ type }}
</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">Other options</span>
<HuiButton
@click="
open('Button labels are Submit and Keep editing', {
confirmButtonText: 'Submit',
cancelButtonText: 'Keep editing'
})
"
>
Custom labels
</HuiButton>
<HuiButton
@click="
open('The Cancel button uses the danger type', {
cancelButtonType: 'danger',
cancelButtonText: 'Discard'
})
"
>
Cancel button type
</HuiButton>
<HuiButton @click="open('Only the Cancel button', { showConfirmButton: false })">
Hide the Confirm button
</HuiButton>
<HuiButton
@click="open('The confirmation has no Cancel button', { showCancelButton: false })"
>
Hide the Cancel button
</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Checking Before Closing
beforeClose(action) receives only 'confirm', 'cancel' or 'close'; it no longer receives done. Returning false, resolving false, throwing or rejecting blocks closing. Other results, including undefined, allow closing. Exceptions produce a development diagnostic, keep the dialog open and allow a later retry.
The check is exclusive while its Promise is pending. Additional Confirm, Cancel, close-button, overlay or Esc actions do not invoke it again. When Confirm is pressed, a prompt first validates the input and keeps a snapshot of the validated value, then checks closing. The input stays editable while waiting; after approval the snapshot is returned, and edits made while waiting are ignored. External closing, closing and reopening, or unmounting invalidates an older result. Cancellation does not abort the underlying business request. Calling HuiMessageBox.close() directly still bypasses the hook.
The example waits 1.5 seconds after Confirm before closing. Other closing attempts are ignored while waiting; no separate submitting lock is needed:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const result = ref('Not submitted yet')
const status = ref('')
const submit = () => {
HuiMessageBox.confirm('Submit now?', 'Notice', {
beforeClose: async (action) => {
if (action !== 'confirm') return
status.value = 'Submitting; closes after 1.5 seconds'
await new Promise<void>((resolve) => setTimeout(resolve, 1500))
status.value = ''
return true
}
})
.then(() => {
result.value = 'Submitted successfully'
})
.catch((action) => {
result.value = `Not submitted (${action})`
})
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton type="primary" @click="submit">Submit</HuiButton>
<span>{{ status || result }}</span>
</HuiSpace>
</template>
Using callback
callback(action) reports closing without taking over the returned Promise. Confirm still resolves, Cancel rejects with 'cancel', and the close button, Esc, overlay or a direct close() rejects with 'close'. The callback runs first, then the Promise settles with the same action. Even if the callback throws, the Promise does not remain pending, and the application's error handler still receives the exception. Handle cancellation when using callback too.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const callbackResult = ref('No callback received yet')
const promiseResult = ref('Not settled yet')
const open = () => {
promiseResult.value = 'Waiting for an action'
HuiMessageBox.confirm('Observe both callback and Promise on closing', 'Notice', {
callback: (action) => {
callbackResult.value = `callback: ${action}`
}
})
.then(({ action }) => {
promiseResult.value = `resolve: ${action}`
})
.catch((action) => {
promiseResult.value = `reject: ${action}`
})
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="open">Open confirmation</HuiButton>
<span>{{ callbackResult }}</span>
<span>{{ promiseResult }}</span>
</HuiSpace>
</template>
Closing Check Results and Exceptions
Open each of the four checks and confirm to observe whether it closes or stays open. Cancel can still exit after a blocked confirmation. Both callback and Promise results are displayed. The throw/reject examples produce an expected development diagnostic.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const guardResult = ref('Not opened yet')
const guardCallback = ref('No callback yet')
const guardStatus = ref('')
type GuardMode = 'allow' | 'deny' | 'throw' | 'reject'
const openGuard = (mode: GuardMode) => {
guardResult.value = 'Waiting for the result'
HuiMessageBox.confirm(
'Confirm to test the check; Cancel can exit after a blocked check',
'Closing check',
{
beforeClose: (action) => {
if (action !== 'confirm') return
if (mode === 'deny') {
guardStatus.value = 'false blocks closing; dialog remains open'
return false
}
if (mode === 'throw') {
guardStatus.value = 'A thrown error blocks closing; dialog remains open'
throw new Error('Example closing check failure')
}
if (mode === 'reject') {
guardStatus.value = 'A rejection blocks closing; dialog remains open'
return Promise.reject(new Error('Example async check failure'))
}
guardStatus.value = 'Async check pending; repeated actions are ignored'
return new Promise<void>((resolve) =>
setTimeout(() => {
guardStatus.value = 'undefined allows closing'
resolve()
}, 600)
)
},
callback: (action) => {
guardCallback.value = `callback: ${action}`
}
}
)
.then(({ action }) => {
guardResult.value = `resolve: ${action}`
})
.catch((action) => {
guardResult.value = `reject: ${action}`
})
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="openGuard('allow')">Async undefined allows closing</HuiButton>
<HuiButton @click="openGuard('deny')">false blocks closing</HuiButton>
<HuiButton @click="openGuard('throw')">throw blocks closing</HuiButton>
<HuiButton @click="openGuard('reject')">reject blocks closing</HuiButton>
</HuiSpace>
<span>{{ guardStatus }}</span>
<span>{{ guardCallback }}</span>
<span>{{ guardResult }}</span>
</HuiSpace>
</template>
Centering and Rounded Buttons
Set center to true to center the title, content and buttons. The close button remains at the top right. roundButton: true gives the buttons rounded ends.
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxOptions } from '@nscode/handy-ui'
const open = (message: string, options: MessageBoxOptions) => {
HuiMessageBox.confirm(message, 'Notice', { type: 'warning', ...options }).catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open('Title, content and buttons are centered', { center: true })"
>Centered (center)</HuiButton
>
<HuiButton @click="open('Buttons have rounded ends', { roundButton: true })"
>Rounded buttons (roundButton)</HuiButton
>
<HuiButton @click="open('Centered, with rounded buttons', { center: true, roundButton: true })">
Enable both
</HuiButton>
</HuiSpace>
</template>
Closing Through Buttons Only
showClose: false hides the top-right close button, closeOnClickModal: false ignores overlay clicks, and closeOnPressEscape: false ignores Esc. Disable all three to allow closing only through the footer buttons.
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxOptions } from '@nscode/handy-ui'
const open = (message: string, options: MessageBoxOptions) => {
HuiMessageBox.confirm(message, 'Notice', options).catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open('No close button at the top right', { showClose: false })">
Hide close button (showClose)
</HuiButton>
<HuiButton @click="open('Overlay clicks do not close', { closeOnClickModal: false })">
Ignore overlay clicks (closeOnClickModal)
</HuiButton>
<HuiButton @click="open('Esc does not close', { closeOnPressEscape: false })">
Ignore Esc (closeOnPressEscape)
</HuiButton>
<HuiButton
type="primary"
@click="
open('Choose an action to continue', {
showClose: false,
closeOnClickModal: false,
closeOnPressEscape: false
})
"
>
Disable all three
</HuiButton>
</HuiSpace>
</template>
VNode or HTML Content
message accepts a string, a VNode created with h(), or a component. Use the options-object form when passing a VNode.
When dangerouslyUseHTMLString is true, a string message is rendered as HTML; see the usage considerations. Otherwise, strings are plain text and tags appear literally.
<script setup lang="ts">
import { h } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const showVNode = () => {
HuiMessageBox.alert({
title: 'Notice',
message: h('p', ['Order ', h('b', '20260101001'), ' submitted'])
}).catch(() => {})
}
const showHtml = () => {
HuiMessageBox.alert('<strong>Bold content</strong>', 'Notice', {
dangerouslyUseHTMLString: true
}).catch(() => {})
}
const showText = () => {
HuiMessageBox.alert('<strong>Bold content</strong>', 'Notice').catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="showVNode">VNode</HuiButton>
<HuiButton @click="showHtml">HTML string (dangerouslyUseHTMLString)</HuiButton>
<HuiButton @click="showText">Plain string: display tags literally</HuiButton>
</HuiSpace>
</template>
Overlay and Page Scrolling
modal defaults to true. Setting it to false removes the translucent overlay, but the surrounding area still blocks page interaction, and clicks there still follow closeOnClickModal. lockScroll defaults to true, preventing page scrolling while open and restoring it on close.
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
</script>
<template>
<HuiSpace wrap>
<HuiButton
@click="
HuiMessageBox.alert('No translucent overlay', 'Notice', { modal: false }).catch(() => {})
"
>
Hide overlay (modal: false)
</HuiButton>
<HuiButton
@click="
HuiMessageBox.alert('The page remains scrollable while open', 'Notice', {
lockScroll: false
}).catch(() => {})
"
>
Keep scrolling unlocked (lockScroll: false)
</HuiButton>
</HuiSpace>
</template>
Closing All Dialogs
HuiMessageBox.close() closes every current dialog with a fade-out animation. Direct close() calls bypass beforeClose, reject each Promise with 'close' and notify callback('close') when a callback is provided. Each dialog is settled only once.
The example closes its alert after 2 seconds through HuiMessageBox.close(). Reopening keeps only the latest scheduled task. Unmounting cancels pending timers, and a Promise settled early no longer triggers its scheduled closing:
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiMessageBox } from '@nscode/handy-ui'
const status = ref('')
let alive = true
let revision = 0
let timer: ReturnType<typeof setTimeout> | undefined
const clearTimer = () => {
if (timer !== undefined) clearTimeout(timer)
timer = undefined
}
onBeforeUnmount(() => {
alive = false
revision++
clearTimer()
})
const open = () => {
if (!alive) return
const request = ++revision
clearTimer()
const current = () => alive && request === revision
let settled = false
status.value = 'Promise pending'
HuiMessageBox.alert('Calls HuiMessageBox.close() automatically after 2 seconds', 'Notice')
.then(() => {
settled = true
if (!current()) return
clearTimer()
status.value = 'Confirm clicked; Promise resolved'
})
.catch((action) => {
settled = true
if (!current()) return
clearTimer()
status.value = `Promise rejected: ${action}`
})
timer = setTimeout(() => {
timer = undefined
if (settled || !current()) return
HuiMessageBox.close()
if (current()) status.value = 'HuiMessageBox.close() called; waiting for the close result'
}, 2000)
}
</script>
<template>
<HuiButton @click="open">Open; close all after 2 seconds</HuiButton>
<p style="margin-top: 12px">{{ status || 'Not opened yet' }}</p>
</template>
Calling the API
| Syntax | Description |
|---|---|
HuiMessageBox(message, title?, options?) | Opens a dialog with the supplied options. Defaults to only a Confirm button and no input |
HuiMessageBox(message, options?) | Same as above, without a title |
HuiMessageBox(options) | Same as above, with all values in the options |
HuiMessageBox.alert(...) | Alert; hides Cancel by default |
HuiMessageBox.confirm(...) | Confirmation; shows Cancel by default |
HuiMessageBox.prompt(...) | Input prompt; shows Cancel by default and uses a localized placeholder |
HuiMessageBox.close() | Closes all current dialogs and returns nothing |
alert, confirm and prompt support all three forms: (message, title, options), (message, options) and (options). Explicit showCancelButton or inputPlaceholder options take precedence.
All three prompt forms return Promise<MessageBoxPromptData>, so value: string can be used directly. Direct calls, alert and confirm return Promise<MessageBoxData>, where value remains optional. Cancellation, closing and callback settlement follow these rules:
| Closing Action | Promise Result |
|---|---|
| Confirm button | Resolves { action: 'confirm', value }, with the input value validated when Confirm was pressed, or an empty string when there is no input |
| Cancel button | Rejects 'cancel' |
| Close button, Esc or overlay click | Rejects 'close' |
Call HuiMessageBox.close() | Rejects 'close' and also notifies callback('close') when provided |
Routing and Global Components in Content
VNodes or components passed through message use the application's context. They can access globally registered components, routing (<RouterLink>, useRouter()), plugins such as Pinia and i18n, and values from app.provide.
- Full installation with
app.use(HandyUI)sets this up automatically. - For on-demand imports, call
setAppContext(app)once in your entry file:
// main.ts
import { createApp } from 'vue'
import { setAppContext } from '@nscode/handy-ui'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
setAppContext(app)
app.mount('#app')
import { h } from 'vue'
import { RouterLink } from 'vue-router'
import { HuiMessageBox } from '@nscode/handy-ui'
HuiMessageBox.confirm(
h('span', [
'This document is referenced. ',
h(RouterLink, { to: '/refs' }, () => 'View references')
]),
'Notice'
).catch(() => {})
When a page contains multiple Vue applications, such as micro frontends, set appContext in the options for a particular call to choose its application. It takes precedence over the default: HuiMessageBox({ message: '...', appContext: otherApp._context }).
HuiConfigProvider belongs to the component tree. Function calls cannot read its size or zIndex, regardless of whether an application context is set.
Options
| Option | Type | Default | Description |
|---|---|---|---|
| title | string | — | Title |
| message | string | VNode | Component | — | Content |
| type | 'success' | 'warning' | 'info' | 'error' | — | Type, displaying its icon before the title. No icon when omitted |
| zIndex | number | Increases from 2001 | Stacking level. When omitted, each new dialog increases the level by 1 and appears above earlier dialogs |
| confirmButtonText | string | Localized Confirm | Confirm label. Explicit empty strings do not fall back |
| cancelButtonText | string | Localized Cancel | Cancel label. Explicit empty strings do not fall back |
| confirmButtonType | 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default' | 'primary' | Confirm button type |
| cancelButtonType | 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default' | 'default' | Cancel button type |
| showConfirmButton | boolean | true | Whether to show Confirm |
| showCancelButton | boolean | false | Whether to show Cancel. Defaults to true for confirm and prompt |
| showClose | boolean | true | Whether to show the top-right close button |
| closeOnClickModal | boolean | true (false for alert) | Whether overlay clicks close the dialog. Explicit settings take precedence |
| closeOnPressEscape | boolean | true (false for alert) | Whether Esc closes the dialog. Explicit settings take precedence |
| center | boolean | false | Whether to center the title, content and buttons |
| roundButton | boolean | false | Whether to use rounded buttons |
| dangerouslyUseHTMLString | boolean | false | Whether to render a string message as HTML |
| modal | boolean | true | Whether to display the overlay |
| lockScroll | boolean | true | Whether to lock page scrolling while open |
| beforeClose | (action: MessageBoxAction) => boolean | void | Promise<boolean | void> | — | Exclusive closing check. Only false, throws or rejections block; undefined allows closing |
| callback | (action: MessageBoxAction) => void | - | Closing notification. The Promise still resolves or rejects normally with the same action |
| inputPlaceholder | string | — | Input placeholder, localized by default for prompt. Explicit empty strings do not fall back. Configuring it shows an input |
| inputPattern | RegExp | — | Regular expression checked on confirmation. Configuring it shows an input |
| inputValidator | (value: string) => boolean | string | — | Validates on confirmation. False or a string indicates failure. Configuring it shows an input |
| inputErrorMessage | string | Localized invalid-input message | Default validation message. Empty strings fall back to the locale; an error returned by the validator takes precedence |
| appContext | AppContext | null | — | Application context for rendering; see Routing and Global Components in Content. Defaults to the application set by app.use(HandyUI) or setAppContext(app) |
| width | string | number | — | Actual panel width; numbers use px. The default maximum width is 90vw |
| class | HTMLAttributes['class'] | — | Class on the actual panel, accepting strings, arrays and objects; does not style the overlay |
| style | StyleValue | — | Panel styles, accepting objects, arrays or CSS strings; matching properties override width |
| inputValue | string | '' | Initial draft for this call. An empty string is valid; later configuration changes do not overwrite edits. Providing it shows an input |
| inputType | MessageBoxInputType | 'text' | text, password, number or textarea. Number returns a string; textarea confirms with Ctrl/Cmd+Enter |
Types
import type {
MessageBoxType,
MessageBoxMessageType,
MessageBoxAction,
MessageBoxInputType,
MessageBoxProps,
MessageBoxOptions,
MessageBoxData,
MessageBoxPromptData,
MessageBoxInstance,
MessageBoxShortcut,
MessageBoxPromptShortcut,
MessageBoxFn
} from '@nscode/handy-ui'
import type { AppContext, Component, HTMLAttributes, StyleValue, VNode } from 'vue'
type MessageBoxType = 'alert' | 'confirm' | 'prompt'
type MessageBoxMessageType = 'success' | 'warning' | 'info' | 'error'
type MessageBoxAction = 'confirm' | 'cancel' | 'close'
type MessageBoxInputType = 'text' | 'password' | 'number' | 'textarea'
interface MessageBoxProps {
title?: string
message?: string | VNode | Component
type?: MessageBoxMessageType
zIndex?: number
width?: string | number
/** Defaults to the active locale; explicit empty strings do not fall back */
confirmButtonText?: string
/** Defaults to the active locale; explicit empty strings do not fall back */
cancelButtonText?: string
confirmButtonType?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default'
cancelButtonType?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default'
showConfirmButton?: boolean
showCancelButton?: boolean
showClose?: boolean
closeOnClickModal?: boolean
closeOnPressEscape?: boolean
center?: boolean
roundButton?: boolean
dangerouslyUseHTMLString?: boolean
beforeClose?: (action: MessageBoxAction) => boolean | void | Promise<boolean | void>
callback?: (action: MessageBoxAction) => void
/** prompt defaults to the active locale; explicit empty strings do not fall back */
inputPlaceholder?: string
inputValue?: string
inputType?: MessageBoxInputType
inputPattern?: RegExp
inputValidator?: (value: string) => boolean | string
/** Omitted or empty values use the active locale; the validator's own error text takes precedence */
inputErrorMessage?: string
modal?: boolean
lockScroll?: boolean
}
interface MessageBoxOptions extends MessageBoxProps {
class?: HTMLAttributes['class']
style?: StyleValue
/** Application context for rendering; defaults to the application set by app.use(HandyUI) or setAppContext(app) */
appContext?: AppContext | null
}
interface MessageBoxData {
value?: string
action: MessageBoxAction
}
interface MessageBoxPromptData {
action: 'confirm'
value: string
}
interface MessageBoxInstance {
id: string
vm: HTMLElement
props: MessageBoxOptions
close: () => void
}
/** Three call forms supported by alert and confirm */
interface MessageBoxShortcut {
(message: string, title?: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(message: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(options: MessageBoxOptions): Promise<MessageBoxData>
}
interface MessageBoxPromptShortcut {
(message: string, title?: string, options?: MessageBoxOptions): Promise<MessageBoxPromptData>
(message: string, options?: MessageBoxOptions): Promise<MessageBoxPromptData>
(options: MessageBoxOptions): Promise<MessageBoxPromptData>
}
interface MessageBoxFn {
(message: string, title?: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(message: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(options: MessageBoxOptions): Promise<MessageBoxData>
alert: MessageBoxShortcut
confirm: MessageBoxShortcut
prompt: MessageBoxPromptShortcut
close(): void
}
MessageBoxInstance is an internal record type for each dialog; callers do not receive an instance. HuiMessageBoxComponent, the component used internally to render dialogs, is also exported. Direct use is usually unnecessary.