[Vuejs]-Vue keydown event only firing on click on DIV

0👍

I’m not sure what your use case is for this but normally you would use the keydown event on an input and not a div in order for it to work. And in your case, since you only want to listen to the escape event, you can make things easier by adding a simple modifier to your event @keydown.esc="handleEscKey", which will trigger only when pressing ESC.

If you want to make the div respond to that event, I found this solution where you make the div a focusable element by adding a tabIndex to it, but I wouldn’t recommend it because you still need to be focused on that div in order for the event to fire and depending on the use case it might interfere with the page accessibility.

If you want to fire the escape at any time without being focused on an input or a div, then I would go with your second solution. You could make it reusable by creating a composable that would have the keydown event listener logic, and then import it on your component.

This will be your composable

import { onMounted, onUnmounted } from "vue";

export function useEscapeEvent(methodToTrigger) {
  const handleEscKey = (e) => {
    if (e.key === "Escape") {
      methodToTrigger();
    }
  };

  onMounted(() => window.addEventListener("keydown", handleEscKey));
  onUnmounted(() => window.removeEventListener("keydown", handleEscKey));
}

And this will be your vue component

  <script setup>
        
        import { useEscapeEvent } from "../composables/escape";
        const printEscape = () => {
            console.log('escape is pressed')
        }    
    
        useEscapeEvent(printEscape);
    </script>

Leave a comment