Handle key press by function in VueJs
You can attach your event handler to window
, that way you can receive all key events and act accordingly depending on your modal's state:
Vue.component('modal', {
template: '<div>test modal</div>',
});
new Vue({
el: "#app",
created() {
window.addEventListener('keydown', (e) => {
if (e.key == 'Escape') {
this.showModal = !this.showModal;
}
});
},
data: {
showModal: true
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<modal v-show="showModal"></modal>
</div>
Alternatively, you may want to consider using the v-hotkey
directive for key input in Vue (docs, github). This will keep your code relatively clean and simple if you must consider several different key inputs.
1. Install it:
npm i --save v-hotkey
Have Vue 'use' it:
import VueHotkey from "v-hotkey"; Vue.use(VueHotkey);
3. Apply it to your Vue components, like so:
<template>
<modal-window ... v-hotkey="keymap">
...
</modal-window>
</template>
<script>
...
data() {
return {
showModal: false
};
},
computed: {
keymap() {
return {
"esc": this.toggleModal
};
}
},
methods: {
toggleModal() {
this.showModal = !this.showModal;
}
}
</script>
easiest way
<input v-on:keyup.13="whatkey()" type="text"> <br>
looks for if the enter key is pressed then fires a method called whatkey.