But I think to capture the keydown event the element needs to be focussed so it wouldn't work as soon as you focus something else (like a form element inside the modal).
I wrote myself a little mixin for that exact usecase, maybe it helps:
export const Escapable = {
created() {
const escapeHandler = (e) => {
if (e.key === 'Escape' && this.escapableVisible) {
this.escapeHandler();
}
}
document.addEventListener('keydown', escapeHandler);
this.$once('hook:destroyed', () => {
document.removeEventListener('keydown', escapeHandler);
});
}
}
Using it would work like this:
<script>
import { Escapable} from "../mixins/Escapable";
export default {
mixins: [Escapable],
data() {
return {
overlayVisible : false,
}
},
computed: {
escapableVisible() {
return this.overlayVisible;
},
},
methods: {
hide() {
this.overlayVisible = false;
},
escapeHandler() {
this.hide();
},
},
}
</script>
It binds the escape key handler to the whole document but only actually hides the modal if it is currently visible.