Modal mechanism ​
Guides and tips for working with the Modal component.
Data flow ​
A default modal has two events:
@dismiss: emitted when the user clicks the secondary footer button, the close icon in the top-right corner, or the mask behind the modal. This event hides the modal.@resolve: emitted when the user clicks the primary footer button. This event hides the modal.
When you create a modal, you usually redefine these two events to carry more data as event parameters. The caller can then listen to them and control the data flow after the modal hides.
Show and hide ​
1. In <template> ​
This is the simplest way to use a modal. Create a ref and bind it to v-model:shown:
The modal works like a normal Vue component here. Define props, emits, slots, and injections as usual, and all Vue behaviors apply:
2. Programmatically ​
Sometimes, you may want to show a modal, doing something with it, and then expects it to return some data in an imperative manner. You can achieve that by passing an entire Vue component into the open() function injected via the useModal() composable.
PREREQUISITES
To make this work, you must ensure the following conditions are met:
- There must be a
<HModalProvider>placed as an ancestor of whereveruseModal()is called - The modal component passed to
open():- Must place
<HModal>at root and make sureinheritAttrs = trueOR setinheritAttrs = falseand bind all the attrs to<HModal v-bind="$attrs"> - If defined, the following props and events must be bound to
<HModal>:shownprop and@update:shownevents@dismissand@resolveevents
- Must place
To pass props to the modal component, you can use the 2nd argument of open(). The composable is infallible: it always returns a Promise. What the Promise contains depends on whether @dismiss or @resolve was emitted:
- If
@dismissis emitted, thePromisecontains an object withstate = 'dismiss' - If
@resolveis emitted, thePromisecontains an object withstate = 'resolve'and adataarray holding the parameters that@resolvedefines.
Typing
The second argument of open() and the data property are typed automatically, based on the modal component you pass in.
If you don't want automatic typing, you can manually adjust them via generics when calling open(). For example: open<typeof Modal, CustomProps, CustomData>(Modal)
Don't want to await?
You can use onDismiss and onResolve callbacks when passing the 2nd argument to open() instead of awaiting and then checking for the values of state and data.
This also applies to all events defined by the modal component if you want to do something without closing the modal. Every event is a prop with an on prefix.
provide and inject
Every modal component you pass to open() mounts as a direct child of <HModalProvider>. Use this to inject the contexts your modals need: place <HModalProvider> at the right point in the tree, instead of threading data through props and emits.