useModal()
useModal() provides an imperative modal API — await the user's response directly in your business logic without managing v-model state in the template. The modal is rendered by SwModalHost, which is registered at the layout level.
Prerequisite: Place
<SwModalHost />once inapp.vueor your current layout. Projects generated bysw createinclude this by default.
Basic Usage
open() → Promise<boolean>
加载中...
<script setup lang="ts">
const modal = useModal()
async function handleDelete() {
const confirmed = await modal.open({
title: 'Confirm Delete',
description: 'This action cannot be undone. Continue?',
confirmText: 'Delete',
cancelText: 'Cancel',
})
if (confirmed) await deleteItem()
}
</script>
open() returns Promise<boolean>: resolves true when the user confirms, false when they cancel or close.
Common Patterns
Alert (cancel hidden)
加载中...
Two-step dangerous confirm
加载中...
Alert only (hide the cancel button)
Pass an empty string to cancelText to hide the cancel button:
await modal.open({
title: 'Notice',
description: 'The event has ended. Thank you for participating.',
confirmText: 'OK',
cancelText: '',
})
Custom button labels
const ok = await modal.open({
title: 'Place Order',
description: `Total: ¥${total}`,
confirmText: 'Pay Now',
cancelText: 'Not Yet',
})
Return Value
| Name | Type | Description |
|---|---|---|
state | DeepReadonly<Ref<ModalState | null>> | Current modal state (null means no modal is open, read-only reactive) |
open | (options: ModalOptions) => Promise<boolean> | Opens the modal; resolves to whether the user confirmed |
close | (confirmed?: boolean) => void | Manually close the modal; defaults to false |
ModalOptions
| Param | Type | Description |
|---|---|---|
title | string | Modal title text |
description | string | Modal description text |
confirmText | string | Confirm button label, defaults to "确认" |
cancelText | string | Cancel button label, defaults to "取消"; pass '' to hide it |
Notes
- Only one imperative modal can be shown at a time; calling
open()again replaces the current one - For modals with complex custom content (e.g. forms), use declarative
<SwModal>+v-model:openinstead close()can be called manually; it defaults tofalse(equivalent to the user cancelling)