To listen for the “esc” key event on a div component in Vue.js, you can use the @keydown event listener to detect when a key is pressed. Then, you can check if the pressed key is the “Escape” key (which has a key code of 27). Here’s how you can do it:

<template>
 <div @keydown="handleKeyDown" tabindex="0">
   <!-- Your content here -->
 </div>
</template>


<script>
export default {
 methods: {
   handleKeyDown(event) {
     if (event.key === 'Escape') {
       // Handle the "esc" key event
       console.log('Escape key pressed');
       // Add your logic here
     }
   }
 }
}
</script>

 
In this example:

  • We add a @keydown event listener to the div component, which triggers the handleKeyDown method when a key is pressed.
  • In the handleKeyDown method, we check if the pressed key is the “Escape” key (event.key === ‘Escape’).
  • If the “Escape” key is pressed, we can perform any necessary actions or logic inside the handleKeyDown method.

Additionally, we add tabindex=”0″ to the div component to make it focusable and allow it to receive keyboard events. This ensures that the div can receive keyboard events even though it’s not a form element.
Remember that for this to work, the div must be in focus, so users may need to click on it or use other methods to bring it into focus before pressing the “esc” key.

Support On Demand!

Vue