vue.jsvuejs2nuxt.jskeyup

Not able to add @keyup listener to layout component


So I have my outer default.vue layout in nuxt architecture. I'my trying to add @keyup.esc="test" to outer element of default.vue:

<template>
    <div @keyup.esc="test">
        <navigation></navigation>
        <nuxt/>
        <transition name="fade">
            <overlay-modals v-if="showModalLogin || showModalRegister"></overlay-modals>
        </transition>
        <transition name="zoom">
            <div class="modal__outer" v-if="showModalRegister || showModalLogin">
                    <modal-login v-if="showModalLogin"></modal-login>
                    <modal-register v-if="showModalRegister"></modal-register>
            </div>
        </transition>
    </div>
</template>

methods: {
    test() {
        alert('come on...');
    },

test method is never fired which makes me confused.


Solution

  • The keyup event will only be detected by the div when the div has focus, so you have to set tabindex to make it focusable, and you have to give it focus.

    new Vue({
      el: '#app',
      methods: {
        test() {
          console.log("Come on");
        }
      },
      mounted() {
        this.$el.focus();
      }
    });
    <script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
    <div id="app" @keyup.esc="test" tabindex="0">
      Here is my div
    </div>