# vuejs-confirm-dialog
Convert your dialogs to async functions and use them all over your project!
This plugin just makes it simple to create, reuse, promisify and build chains of modal dialogs in Vue.js. It provides just one function `createConfirmDialog` that does all the hard work for you.
> New documentation is ready! Try a new [site](https://vcd-docs.netlify.app) that contains all the docs of the project!
> [vcd-docs.netlify.app](https://vcd-docs.netlify.app)
## About
How does it work? The idea is simple, this function -- `createConfirmDialog` gets a modal component and magically provides to it emits `confirm` and `cancel` and its props values. This function returns to you a dialog instance that controls the rendering of the modal component and reacts to user decisions. It reduces you to write all the boilerplate code over and over again and makes it simple to reuse your modals everywhere in your project.
You can work with dialogs like with promises or with hooks that the dialog instance generates for you.
## Breaking changes in v1.0
- **Vue 2 is no longer supported.** `v1.0.0` targets Vue 3 (`^3.5.0`) only. If your project is on Vue 2, use the `legacy` branch / pin to `npm i vuejs-confirm-dialog@^0.6.0`, which is the last release with Vue 2 support (via `vue-demi`).
- **`` is removed.** The library now mounts its own render root automatically the first time you call `reveal()` — delete `` from your app's template, it's no longer needed (and no longer exported).
## SSR / Nuxt
Works with SSR (Nuxt included) as a regular Vue plugin — `app.use(ConfirmDialog)` in your Nuxt plugin/`main.js` is all that's needed, no separate Nuxt module required. Dialogs only ever mount client-side (the render root is created lazily on the first `reveal()`, which only happens in response to user interaction, i.e. after hydration), so nothing touches `document` during the server render.
## Installation
in 2 steps
### Step 0
Add the plugin to your `node_modules`
```bash
npm i vuejs-confirm-dialog
```
### Step 1(recommended)
Install the plugin. This is recommended (not strictly required) — installing it lets dialog components access anything your app provides via plugins/`provide()` (routing, i18n, stores, etc.). Without it, dialogs still work, just without that inherited context.
```js
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import * as ConfirmDialog from 'vuejs-confirm-dialog'
createApp(App).use(ConfirmDialog).mount('#app')
```
And that's it. Now you can use it.
## Usage
Build Modal Window. It must contain emits `confirm` and `cancel`. ~~It also must contain~~ ~~prop `show`~~. ~~Put `v-if="show"` in its template for conditional rendering~~(no longer need to).
```html
```
Use this modal window wherever you want in your project:
```html
```
### Two ways of usage
The plugin lets you decide how to use it. The first way is to use hooks:
- `onConfirm` - hook gets a callback that runs after the user confirmed the modal message
- `onCancel` - run callback if the user decides to click cancel
The second way is promisify modal dialog. `reveal` the function returns a Promise, that resolves data and `isCanceled` boolean from the dialog after the user commits the action.
for example(not real):
```html
```
## Passing data to/from the dialog
It will be not so useful if we will not have the option to pass data to and from а component.
There are several ways to deal with it. First of all, you can pass data to the second argument of the `createConfirmDialog` function. Data must be an object with names of properties matching to props of the component you use as dialog. For example, if a component has a prop with the name `title` we have to pass this `{ title: 'Some Title' }`. So these will be the initial props that the dialog component will receive.
You can change props values during the calling `reveal` function by passing to its object with props data. So you can call the `reveal` function several times with different props. This is an excellent way to reuse the same dialog in different situations.
And finally, you can pass data to emit functions inside your modal dialog component: `confirm` and `cancel`. Hooks `onConfirm` and `onCancel` will receive this data. Also, it will be passed by Promise, so you can use the async/await syntax if you prefer.
With TypeScript, the type of `data` comes from your component's `defineEmits`:
```html
```
```typescript
const { data, isCanceled } = await createConfirmDialog(PickNumberDialog).reveal()
if (!isCanceled) {
data // number | undefined
}
```
Untyped emits (`defineEmits(['confirm', 'cancel'])`) give `any`, as before.
The full example, that displays passing data, reusing, and modal chains:
```html
```
## Props Behavior Options
Unfortunately, the way of passing props is not so clear to the developers. The problem occurs when you try to reuse a dialog instance already created with `createConfirmDialog`. See also the [issue](https://github.com/harmyderoman/vuejs-confirm-dialog/issues/21).
Let's consider this process step by step. Props values are assigned three times, the first time is default props values, in the component, this plugin does not show up on them in any way. The second time occurs on creating an instance of the dialog, let's define these values as initial props. The third time passing values is possible when the user prompts the dialog using the `reveal` method. If you don't set the props behavior options, then each time you pass values, this data will be saved.
For example, if you have an alert component and you called it with the message "Authorization failed!", then next time if you don't pass a new message value, it will show this message again.
Perhaps it will be convenient if every time after closing the dialog, the values of the props will be reset to the initial or even default values. For this functionality, props transfer settings have been added.
That's what the `resetProps` option is for — it decides what happens to props after the dialog closes (confirm, cancel or `close()`):
- `'none'` (default) - keep the last passed values
- `'initial'` - go back to the values passed to `createConfirmDialog`
- `'defaults'` - drop everything, so the component's own prop defaults apply
```javascript
const dialog = createConfirmDialog(
ModalComponent,
{ message: 'Some message...' }, // Initial props values
{ resetProps: 'initial' }
)
```
> The older `chore`/`keepInitial` options still work but are deprecated and will be removed in 2.0 (you'll see a one-time console warning): `{ chore: true, keepInitial: true }` is `resetProps: 'initial'`, `{ chore: true }` is `resetProps: 'defaults'`.
There's also `closeDelay` - milliseconds to wait before unmounting the dialog component after it's closed. Defaults to `0` (unmount immediately). Useful if your modal component has its own exit animation and needs a bit of time on screen after `confirm`/`cancel` before being removed.
```javascript
const dialog = createConfirmDialog(
ModalComponent,
{ message: 'Some message...' },
{ closeDelay: 300 } // give a 300ms exit transition time to finish
)
```
## Updating props of an open dialog
`update(props)` changes props of the dialog at any time, including while it's open — handy for progress dialogs or toasts. The pending `reveal()` promise is not affected.
```javascript
const progress = createConfirmDialog(ProgressToast, { done: 0, total: 40 })
progress.reveal()
for (const [i, file] of files.entries()) {
await upload(file)
progress.update({ done: i + 1 })
}
progress.close()
```
Calling `reveal()` on a dialog that's already open does the same: it updates the props and returns the same pending promise, instead of opening a second copy.
## One instance — one open dialog
An instance from `createConfirmDialog` is one dialog: it's either open or closed. To show several at the same time (toasts, stacked alerts), create an instance per dialog:
```javascript
const toast = (message) => createConfirmDialog(Toast, { message }).reveal()
toast('Saved')
toast('Uploaded 3 files') // both are on screen
```
## Rendering into your own container
By default every dialog renders into a shared root in `document.body`, which is what you want for modals. For things like a toast stack, pass `target` — a CSS selector or an element — and the dialog is teleported there:
```html
```
```javascript
createConfirmDialog(Toast, { message }, { target: '#toast-stack' }).reveal()
```
If the target isn't in the DOM when the dialog is revealed, it falls back to the default root and logs a warning.
### Exit transitions
Dialogs are rendered through Vue's [``](https://vuejs.org/guide/built-ins/transition-group.html), so CSS-based enter/leave transitions work out of the box — just give your modal component's root element matching transition classes (e.g. `.v-leave-active`, `.v-leave-to`), the same way you'd style any `` child. This is independent of `closeDelay` above; use whichever fits your case (or both).
## Using inside Options API
If you prefer you can use it with Options API inside methods.
```javascript
import Dialog from './Dialog.vue'
import { createConfirmDialog } from 'vuejs-confirm-dialog'
export default {
data(){
return {
isConfirmed: false
}
},
methods: {
showDialog(){
const dialog = createConfirmDialog(Dialog)
dialog.onConfirm(() => {
this.isConfirmed = true
})
dialog.reveal()
}
}
}
```
For more info check this full Vue 3 [example](https://github.com/harmyderoman/vuejs-confirm-dialog/blob/main/demos/vue3).
## Close dialogs programmable
Sometimes you need to close dialogs and don't want to wait for the user's action. For these purposes, dialog instance provides method `close`.
```javascript
import Alert from './Alert.vue'
import { createConfirmDialog } from 'vuejs-confirm-dialog'
const dialog = createConfirmDialog(Alert)
dialog.reveal()
setTimeout(() => {
dialog.close()
}, 3000)
```
It doesn't call `onConfirm`/`onCancel`, but the pending `reveal()` promise does resolve — with `{ isCanceled: true, closed: true }` — so `await dialog.reveal()` never hangs:
```javascript
const { isCanceled, closed } = await dialog.reveal()
if (closed) {
// closed from code, not by the user
}
```
If you need to close all dialogs just call `dialog.closeAll()` — it closes each of them the same way.
## Demo
Clone the project, install dependencies and run the following command to see the demo:
```bash
pnpm run demo
```
The demo is styled by beautiful [daisyUI](https://daisyui.com/).
## Vue 2 support (legacy line)
This `0.x` line (`0.6.0` and below) is the **last one to support Vue 2** (via `vue-demi` / `@vue/composition-api`). A future `1.0.0` release will drop Vue 2 support and target Vue 3 only.
If your project is on Vue 2, pin your install to this line so you don't accidentally pick up a `1.0.0+` release later:
```bash
npm i vuejs-confirm-dialog@^0.6.0
```
Vue 2 also needs the `@vue/composition-api` plugin installed and set up in your project (it's an optional peer dependency of this package):
```bash
npm i @vue/composition-api
```
Also you have to add `DialogsWrapper` to `App.vue` template:
```html
```
## Roadmap
* [x] Make it work!
* [x] Make it work without `show` a prop
* [x] TSDoc
* [x] Change testing tools to Vitest
* [x] Improve tests
* [x] Improve docs( reuse, passing props ...)
* [x] More examples
* [x] Fix TypeScript error when the dialog component has default prop values ([#31](https://github.com/harmyderoman/vuejs-confirm-dialog/issues/31))
* [x] `closeDelay` option to support exit transitions ([#34](https://github.com/harmyderoman/vuejs-confirm-dialog/issues/34))
* [x] Drop Vue 2 support, Vue 3 only `1.0.0`
* [x] Auto-mounted render root — no more manually placing ``
* [x] Native `` support for exit transitions
* [x] `close()` resolves the `reveal()` promise, `update()`, `target`, typed `data`, `resetProps` (`1.1.0`)
## Thanks
Inspired by [`Vueuse`](https://github.com/vueuse/vueuse) and [`vue-modal-dialogs`](https://github.com/hjkcai/vue-modal-dialogs). Thanks to all creators of these projects ❤️!
Keep calm and support :ukraine:!