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 in app.vue or your current layout. Projects generated by sw create include 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

NameTypeDescription
stateDeepReadonly<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) => voidManually close the modal; defaults to false

ModalOptions

ParamTypeDescription
titlestringModal title text
descriptionstringModal description text
confirmTextstringConfirm button label, defaults to "确认"
cancelTextstringCancel 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:open instead
  • close() can be called manually; it defaults to false (equivalent to the user cancelling)