PageHost
Place a host in each page that displays messages or dialogs. Each page manages its own feedback when the user switches pages.
Import
In uni-app, configure easycom and use <hui-page-host>. In plain Vue 3, install the plugin from the @nscode/handy-uni/web preview and use the same tag. Import usePageHost from @nscode/handy-uni in the page script to obtain the page host.
Examples
Default message and dialog
<hui-page-host> creates and registers the page host. Query it with usePageHost() in page event handlers after mounting. The child host does not exist while the page's own setup runs, so do not capture that early query result. Without custom slots, the host renders the actual Toast, Dialog and ImagePreview components. A regular toast displays message ?? title and closes after 2 seconds by default; duration: 0 keeps it until the returned close() is called. Dialogs accept title, message and native option mappings such as content, confirmText and cancelText. Set showCancel: true explicitly when a cancel button is needed. Press the buttons and read the result on the page.
<template>
<view>
<hui-page-host>
<button @click="save">Show a message</button>
<button @click="pin">Show a sticky message</button>
<button @click="unpin">Close the sticky message</button>
<button @click="remove">Delete record</button>
<button @click="inform">Confirm only</button>
<text>{{ result }}</text>
</hui-page-host>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { usePageHost } from '@nscode/handy-uni'
function host() {
const current = usePageHost()
if (!current) throw new Error('Mount hui-page-host first')
return current
}
const result = ref('Waiting')
let pinned: { close(): void } | undefined
const save = () => {
host().toast.open({ title: 'Saved' })
result.value = 'The message closes after 2 seconds'
}
const pin = () => {
pinned = host().toast.open({ title: 'Syncing', duration: 0 })
result.value = 'The sticky message stays open'
}
const unpin = () => {
pinned?.close()
pinned = undefined
result.value = 'The sticky message is closed'
}
const remove = async () => {
try {
await host().dialog.open({
title: 'Delete record',
content: 'This cannot be undone.',
showCancel: true,
confirmText: 'Delete',
cancelText: 'Keep'
})
result.value = 'Deleted'
} catch (reason) {
result.value = 'Not deleted, reason: ' + String(reason)
}
}
const inform = async () => {
try {
await host().dialog.open({
title: 'Submitted',
content: 'You will be notified of the review result.',
showCancel: false
})
result.value = 'Acknowledged'
} catch (reason) {
result.value = 'Dialog ended, reason: ' + String(reason)
}
}
</script>
Opening several dialogs
When a dialog is already open, concurrency decides what happens to the new one: queue (default) waits until the current one ends; replace takes over at once and the current one ends with replaced; reject does not open and ends with rejected. Each button opens two dialogs in a row, and the page lists both results.
<template>
<view>
<hui-page-host>
<button @click="run('queue')">Queue</button>
<button @click="run('replace')">Replace</button>
<button @click="run('reject')">Reject</button>
<text v-for="(line, index) in log" :key="index">{{ line }}</text>
</hui-page-host>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { usePageHost } from '@nscode/handy-uni'
function host() {
const current = usePageHost()
if (!current) throw new Error('Mount hui-page-host first')
return current
}
const log = ref<string[]>([])
function track(name: string, task: Promise<{ action: 'confirm' }>) {
task.then(
() => log.value.push(name + ': confirmed'),
(reason) => log.value.push(name + ': ' + String(reason))
)
}
function run(mode: 'queue' | 'replace' | 'reject') {
log.value = ['concurrency: ' + mode]
track('First', host().dialog.open({ title: 'First', content: 'Opened first' }))
track(
'Second',
host().dialog.open({ title: 'Second', content: 'Opened second', concurrency: mode })
)
}
</script>
Custom message and dialog content
Show a short message or open a dialog and choose a response. The page displays the result. The example replaces the host's message and dialog contents with the toast and dialog slots.
<template>
<view>
<hui-page-host>
<button @click="notify">Show a message</button>
<button @click="confirm">Open dialog</button>
<text>{{ result }}</text>
<template #toast="{ options }">
<view role="status" aria-live="polite">
<text v-if="options">{{ options.message ?? options.title }}</text>
</view>
</template>
<template #dialog="{ options, settle }">
<view>
<text>{{ options.message ?? options.content }}</text>
<button @click="settle('cancel')">Cancel</button>
<button @click="settle('confirm')">Confirm</button>
</view>
</template>
</hui-page-host>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { usePageHost } from '@nscode/handy-uni'
function host() {
const current = usePageHost()
if (!current) throw new Error('Mount hui-page-host first')
return current
}
const result = ref('Ready')
const notify = () => host().toast.open({ message: 'Saved', duration: 1500 })
const confirm = async () => {
try {
await host().dialog.open({ message: 'Send this report?' })
result.value = 'Confirmed'
} catch {
result.value = 'Closed'
}
}
</script>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
host | PageHost | Host created by this component | Binds an existing controller. Replacing it switches the rendered host. Clearing an initially explicit binding hides its content; omitting the initial binding creates and registers this page's host. |
The root element accepts the common props.
Events
None.
Slots
| Slot | Arguments | Description |
|---|---|---|
default | None | Page content |
toast | { options } | Custom persistent live region. options holds toast options or is undefined when idle; display options.message ?? options.title. |
dialog | { options, settle } | Custom dialog. settle('confirm' / 'cancel' / 'close') requests closing through configured guards. |
Methods
| Method | Signature | Description |
|---|---|---|
getHost | (): PageHost | undefined | Returns the host currently rendered by this view. Switching host returns the new host; clearing an initially explicit binding returns undefined. |
activate | (): void | Activates this registered host for subsequent functional feedback when a page has multiple hosts. Unmounting falls back to a remaining host. |
Types
Import PageHostProps, PageHostExpose and PageHost from @nscode/handy-uni. usePageHost() returns PageHost | undefined.
Without custom slots, the host renders the actual Toast, Dialog and ImagePreview components. A dialog settles its Promise when closing starts, and advances the queue only after its leave animation. Handle rejection for cancellation, closing and unmounting. A custom dialog slot has no default animation; the controller applies its guards, settles and advances it.
Toast handles support close() and update(patch); stale handles cannot alter a newer toast. Keep the live region mounted and insert message content when needed. Fixed NavBar components cache their bottom boundaries per page, so either mounting order works and multiple registrations remain independent.
usePageHost() only queries an existing host. Descendants prefer the injected host during setup; page event handlers query the current page. It returns undefined when none exists. Pass a page key to query another registered page with usePageHost(pageKey). Only <hui-page-host> creates and registers a page host and unregisters it on unmount; standalone Toast and NavBar components do not create hosts. Function calls fall back to native feedback in uni when there is no host; Web function calls automatically mount a real PageHost. Host fields:
| Field | Type | Description |
|---|---|---|
pageKey | string | Identifies the page that owns the host, set from the current page when mounted |
toast.current | ShallowRef<message options | undefined> | The message on screen, or undefined |
toast.open(options) | (options: message options) => { close(): void; update(patch): void } | Shows a toast and replaces the previous one; the handle only closes or updates this toast |
dialog.current | ShallowRef<{ options, requestClose, ... } | undefined> | Current dialog; requestClose('confirm' / 'cancel' / 'close') applies closing guards |
dialog.open(options) | (options: dialog options) => Promise<{ action: 'confirm' }> | Opens a dialog. Resolves on confirm; every other ending rejects with a reason string, see below |
preview.current | ShallowRef<{ options, requestClose, ... } | undefined> | Current custom image preview |
preview.open(options) | (options: ShowImagePreviewOptions) => { close(): void } | Opens or replaces a custom image preview and returns its closing handle |
dispose() | () => void | Closes the toast and preview and ends all dialogs with unmounted. Called on unmount, rarely needed |
Message options:
| Field | Type | Default | Description |
|---|---|---|---|
message, title | string | — | Message text; message takes precedence and title preserves the native option mapping |
type | 'text' | 'success' | 'fail' | 'warning' | 'loading' | 'text' | Actual Toast status icon; loading displays a loading indicator |
duration | number | 2000 | Milliseconds on screen; loading defaults to 0, 0 stays open, negative or non-finite values fall back to 2000 |
icon | string | Based on type | Custom icon name, overriding the default icon except for loading |
position | 'top' | 'middle' | 'bottom' | 'middle' | Toast position |
forbidClick | boolean | false | Blocks page clicks while the toast is visible |
mask | boolean | — | Native toast fallback option; use forbidClick for the actual Toast component |
onClose | () => void | — | Called when this toast closes or is replaced |
Dialog options:
| Field | Type | Default | Description |
|---|---|---|---|
title | string | — | Title. The title row is hidden when omitted |
message, content | string | — | Body text; message takes precedence |
showCancelButton, showCancel | boolean | false | Whether to show cancel; the first option takes precedence |
showConfirmButton | boolean | true | Whether to show confirm |
cancelButtonText, cancelText | string | Cancel text from the current locale | Cancel button text; the first option takes precedence |
confirmButtonText, confirmText | string | Confirm text from the current locale | Confirm button text; the first option takes precedence |
beforeConfirm | () => unknown | — | Runs before confirmation; false, thrown errors and rejected Promises block it |
beforeClose | (action) => unknown | — | Runs before closing for confirm, cancel and close actions |
cancelColor, confirmColor | string | — | Not used by the default dialog; a custom dialog slot can read them |
concurrency | 'queue' | 'replace' | 'reject' | 'queue' | When a dialog is open: queue waits until it ends, replace takes over at once, reject does not open |
Rejection reasons of dialog.open:
| Reason | When |
|---|---|
cancel | The cancel button was pressed, or a custom slot called settle('cancel') |
close | The topmost dialog passed closing guards. App and uni-H5 pages use onBackPress((e) => e.from === 'backbutton' && closeTopLayer()) to distinguish the physical back button from programmatic navigation |
replaced | A new dialog opened with concurrency: 'replace' took over |
rejected | Opened with concurrency: 'reject' while another dialog was open |
unmounted | The page that owns the host unmounted, or open was called on a host whose page had unmounted |
Platform notes
| Behavior | uni-app H5 | WeChat Mini Program | App-vue | Plain Vue 3 Web (preview) |
|---|---|---|---|---|
| Mounting | One host per page | One per page; message ownership during tab cold starts and switches awaits device checks in the smoke checklist | One per page; whether it covers the native navigation bar and native components awaits device checks in the smoke checklist | Supports explicit hosts and an automatic global host for function calls |
| Unmounting | The current message closes and pending dialogs settle | Same as H5 | Same as H5 | Unmounting an explicit host settles its dialogs |
Do not use preloadPage to verify Vue page-instance keys: uni-H5 only preloads code, and App uses nvue preloading; neither creates the corresponding Vue page instance. Simulator and desktop-browser readings do not replace device verification. See the device smoke checklist for the verification steps.