How can i close a vuetify's dialog opened without an activator, when the user press the ESC key on the keyboard?
to listen for esc key presses with the @keydown. esc directive. And if the event is triggered, we set dialog to false to close the dialog.
We can use Esc key to close dialogue boxes or any custom popup modals. Here we will discuss even handling on ESC key press in which we can fire any event we want.
Some windows can be closed by pressing the esc key, like the Preference window in any app or the 'Safari help' window or the 'Fonts' window in TextExit for example. Other windows can not be closed by pressing the esc key, like the Safari browser window or the 'Special Characters' window.
Add @keydown.esc="dialog = false"
to v-dialog
component
<v-dialog v-model="dialog" @keydown.esc="dialog = false"></v-dialog> data: () => ({ dialog: false }),
Working example: https://codepen.io/anon/pen/BJOOOQ
Additionally, if using dialog as custom component then possibly we need to emit input event:
<template> <v-dialog :value="value" @keydown.esc="$emit('input')"> ...
This is the only way I was able to get it to work
mounted() { // Close modal with 'esc' key document.addEventListener("keydown", (e) => { if (e.keyCode == 27) { this.$emit('close'); } }); },
this code maybe can help you
mounted() {
let self = this;
window.addEventListener('keyup', function(event) {
// If ESC key was pressed...
if (event.keyCode === 27) {
// try close your dialog
self.advanced_search = false;
}
});
},
the same principle as adding keypress binding to any vue component should work - add the following code to the v-dialog component :
@keydown.esc="dialog = false"
working example ( note the close button click event handler as well )
https://codepen.io/yordangeorgiev/pen/WBeMGq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With