Dialogs are those thingies that popup on your UI and are handy to allow users to perform actions without navigating away from the screen.
For example, here’s one that enables users to create new request..
.. and here’s an example from Vuetify site that shows a short message.
The v-dialog
component is the recommended way to show confirmation dialogs too.
While confirmation dialogs are great, they could get annoying if used in three hundred different places. For e.g. what do you do if you need a yes/no confirmation dialog?
Fortunately, we can create a distinct component for reusable confirmation dialogs as easily. Here’s a simple way to do that.
First, create a component ConfirmDlg.vue
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
<template>
<v-dialog
v-model="dialog"
:max-width="options.width"
:style="{ zIndex: options.zIndex }"
@keydown.esc="cancel"
>
<v-card>
<v-toolbar dark :color="options.color" dense flat>
<v-toolbar-title class="text-body-2 font-weight-bold grey--text">
{{ title }}
</v-toolbar-title>
</v-toolbar>
<v-card-text
v-show="!!message"
class="pa-4 black--text"
v-html="message"
></v-card-text>
<v-card-actions class="pt-3">
<v-spacer></v-spacer>
<v-btn
v-if="!options.noconfirm"
color="grey"
text
class="body-2 font-weight-bold"
@click.native="cancel"
>Cancel</v-btn
>
<v-btn
color="primary"
class="body-2 font-weight-bold"
outlined
@click.native="agree"
>OK</v-btn
>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<script>
export default {
name: "ConfirmDlg",
data() {
return {
dialog: false,
resolve: null,
reject: null,
message: null,
title: null,
options: {
color: "grey lighten-3",
width: 400,
zIndex: 200,
noconfirm: false,
},
};
},
methods: {
open(title, message, options) {
this.dialog = true;
this.title = title;
this.message = message;
this.options = Object.assign(this.options, options);
return new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
},
agree() {
this.resolve(true);
this.dialog = false;
},
cancel() {
this.resolve(false);
this.dialog = false;
},
},
};
</script>
|
Next, use the confirm dialog in a component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<template>
<!-- other code -->
<ConfirmDlg ref="confirm" />
</template>
<script>
export default {
components: {
ConfirmDlg: () => import("./ConfirmDlg"),
},
methods: {
async delRecord() {
if (
await this.$refs.confirm.open(
"Confirm",
"Are you sure you want to delete this record?"
)
) {
this.deleteRecord();
}
},
deleteRecord() {
console.log("Record deleted.");
},
},
};
</script>
|
And voila.
Here’s a Codepen with a working example.