0

As the title says, I can't get my event to fire ON a div, only when I click on the page, in terms od accessibility, the user should be able to click on the esc key, directly, and not after clicking on the page.

This is how it is now on my div:

@keydown="handleEscKey($event)"

then my function

const handleEscKey = (event: KeyboardEvent) => {
  emit("close")
}

This is another option, of how I have tried, that works. I have removed the @keydown event and used this:

  const handleEscKey = (e: KeyboardEvent) => {
      if (e.shiftKey) {
        emit("close")
      }
    }
// Event listeners for "Esc" and "Enter" keys
onMounted(() => {
  window.addEventListener('keydown', handleEscKey);
});

// Remove event listeners on component unmount
onBeforeUnmount(() => {
  window.removeEventListener('keydown', handleEscKey);
});

Is there any answer of how to use @keydown event from vue?

Non404
  • 1,130
  • 2
  • 12
  • 22

1 Answers1

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>
Selka
  • 1
  • 1