Listening to “esc” Key Event on Div Component in Vue.js

Vue 3 offers several ways to handle the ESC key. This guide covers approaches for local, global, and reusable implementations.

Summarize with AI

Not enough time? get the key points instantly.

In modern interfaces, listening to the Escape key is key to good UX, especially for modals and overlays. Vue 3 makes it easy to listen to the “esc” key on specific components like a div using modifiers or the Composition API.

Using @keyup.esc on a Focusable

Use Vue’s native event modifiers by making the

focusable using tabindex.

  

    Press ESC inside this box to trigger an action.

  

 

Note: tabindex=”0″ makes the

keyboard focusable so it can detect key events.

Composition API Approach (Window-Level Listener)

This works even if the div isn’t focused, useful for global ESC behavior (e.g. modal closing).

Note: Attach the event listener to window for global behavior regardless of where the focus is.

Also Read:

Custom Directive (Reusable Pattern)

For reusable use across components, you can define a custom directive.

// v-esc.jsexport default {

  mounted(el, binding) {

    el._escHandler = (e) => {

      if (e.key === ‘Escape’) binding.value(e)

    }

    document.addEventListener(‘keydown’, el._escHandler)

  },

  unmounted(el) {

    document.removeEventListener(‘keydown’, el._escHandler)

  }

}

  

Esc will trigger this

 

Note: Custom directives let you abstract key event logic and reuse it anywhere in your app.

Also Read: Best Vue Component Libraries to Build Stunning Frontends

Conclusion

Listening to the Escape key in Vue 3 can be done through native modifiers, global listeners, or custom directives, depending on the level of control needed.

Related Resources

  • Vue 3 Event Modifiers
  • Keyboard Accessibility Guide (MDN)
  • Vue 3 Composition API Basics


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.