Vue JS: Listening to Key Events Using Computed Properties and V-model
There are many times that you want to listen to key events, in my case the esc key events when closing modals, popups, etc. Listening to key events in a Vue instance may not work because the key events are dispatched from the body
tag that the Vue cannot control, unless the element in Vue can be focused (Using tableIndex
attribute may help here).
In my case as I am using Quasar framework and want to listen to the esc key events on a Quasar modal element, so I could not use the tableIndex
trick to focus the element. By default, the modal element gets unmounted when the esc key is pressed.
My goal is to reset all the data related to the modal once the modal is closed either by clicking a close button or pressing the esc key. Basically, I want to make sure the closeModal
function is executed when the esc key is pressed.
There should be other workarounds to achieve the result, but here’s what I did using computed
properties in Vue. The good thing was that the Quasar modal element can use v-model
attribute to bind the computed property.
Firstly, you have a boolean state that changes once the openModal
or closeModal
function is executed, for example, isModalOpen
.
Then, using a computed
property and its setter, we can execute closeModal
function whenever the computedIsModalOpen
changes to false. For example:
computed: {
computedIsModalOpen: {
get() {
return this.isModalOpen;
}, set(value) {
if (!value) {
this.closeModal();
} else {
this.isModalOpen = value;
}
},
},...}methods: {
closeModal() {
const vm = this;
vm.isModalOpen = false;
vm.selectedStatus = false;
vm.modalItemInput = {}; }
}
Then, the key point is that the computedIsModalOpen
is bound to the modal element by v-model
. This makes that when its value changes, the setter gets executed and then the closeModal
function.
When the modal is open again, isModalOpen
will be changed to true,
and so will computedIsModalOpen
.
<q-modal
v-model=”computedIsModalOpen”>
...
</q-modal