I\'m expecting that \'close\' event is fired when I\'m clicking ESC button being on \"shadow-modal\" div, but it\'s not happening
vue 2.5.13, any ideas why?
While DmitrySemenov solution works for me it's not the best solution when you have multiple modals on the page. I tried it and I discovered it fires close event for every modal.
I think the best way to do it is registering a "keyup" event when the modal is shown and deregistering it after hide. It gives you an advantage because the event is registered only when it's needed. To do it you need to add a watcher for "show" property:
props: {
show: {
type: Boolean,
default: false
}
},
watch: {
show() {
if (this.show === false) {
window.removeEventListener("keyup", this.onEscapeKeyUp);
} else {
window.addEventListener("keyup", this.onEscapeKeyUp);
}
}
},
methods: {
onEscapeKeyUp(event) {
if (event.which === 27) {
this.$emit("close");
}
}
}
The modal should have v-if="show"
that controls modal's visibility:
Whole solution code (you can see it on codesandbox.io):
Modal.vue
App.vue
First Modal
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rem beatae
repellat dolores deleniti illum voluptatem facilis neque ut placeat,
eius iusto tempore! Totam omnis non tempore perferendis expedita numquam
neque!
Second Modal
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rem beatae
repellat dolores deleniti illum voluptatem facilis neque ut placeat,
eius iusto tempore! Totam omnis non tempore perferendis expedita numquam
neque!