Listening for the esc key event on a div component in Vue.js

I want to listen to the esc key event to call a method in the Vue component. The docs show this example:

<input v-on:keyup.enter="submit">

but I use <div></div>, and you need to catch the event from the outside. However, I do not want to overload global handlers or anything like that.

Any suggestions?

+16
source share
4 answers

For those who wander here from Google, in Vue 2 ...

<div @keydown.esc="something_in_your_methods"></div>
+26
source

You can not. Key events are dispatched from the body tag, and Vue cannot be connected to the tag <body>.

Sourced from "When VueJS Can't Help You"]

You will need to configure your own event listener.

( VueJS )

+4

, .

close.js

export default {
    created() {
        let that = this;

        document.addEventListener('keyup', function (evt) {
            if (evt.keyCode === 27) {
                that.close();
            }
        });
    },
};

Import and use it in the desired component

import closeMixin from './../../mixins/close.js';

export default {
    mixins: [closeMixin],
    props: [],
    computed: {}
    methods: {
        close(){
            // closing logic
        }
    }
}
+3
source

The secret to creating keydownevents is working on divs and other non-formatted elements to add tabindexan attribute:

<div tabindex="0"
    @keydown.left="previousImage"
    @keydown.right="nextImage" />

Now the div has become a focusable element, and key events will be triggered.

Here is more information about focusable elements and tabindex

+2
source

Source: https://habr.com/ru/post/1683250/


All Articles