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 <div>
Use Vue’s native event modifiers by making the <div> focusable using tabindex.
<template> <div @keyup.esc="close" tabindex="0"> Press ESC inside this box to trigger an action.
</div>
</template>
<script>
export default {
methods: {
close() {
console.log("ESC key pressed");
}
}
}
</script>
Note: tabindex="0" makes the <div> 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).
<script setup>import { onMounted, onBeforeUnmount } from 'vue'
function handleKeydown(e) {
if (e.key === 'Escape') {
console.log('ESC pressed globally')
}
}
onMounted(() => {
window.addEventListener('keydown', handleKeydown)
})
onBeforeUnmount(() => {
window.removeEventListener('keydown', handleKeydown)
})
</script>
Note: Attach the event listener to window for global behavior regardless of where the focus is.
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)
}
}
<template> <div v-esc="handleEscape">Esc will trigger this</div>
</template>
<script>
import escDirective from './v-esc.js'
export default {
directives: { esc: escDirective },
methods: {
handleEscape() {
console.log("ESC pressed via directive")
}
}
}
</script>
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