How to Use Key Modifiers in Vue for Keyboard Events
key modifiers by adding them to event listeners like @keyup.enter to trigger actions only when specific keys are pressed. These modifiers simplify keyboard event handling by filtering keys directly in the template.Syntax
Vue key modifiers are added to event listeners using a dot . followed by the key name or modifier after the event type. For example, @keyup.enter listens for the Enter key on a keyup event.
Common key modifiers include enter, esc, space, tab, and arrow keys like up, down.
You can also use .exact to require exact modifier keys like Ctrl or Shift.
<input @keyup.enter="submit" placeholder="Press Enter to submit">
Example
This example shows a Vue component with an input box that triggers different messages when Enter or Escape keys are pressed.
<template>
<div>
<input
@keyup.enter="onEnter"
@keyup.esc="onEscape"
placeholder="Type and press Enter or Escape"
/>
<p>{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('')
function onEnter() {
message.value = 'You pressed Enter!'
}
function onEscape() {
message.value = 'You pressed Escape!'
}
</script>Common Pitfalls
One common mistake is forgetting that key modifiers only work with keyboard events like keyup or keydown. Using them on other events like click won't work.
Another pitfall is using incorrect key names; Vue uses standardized key names like esc instead of escape.
Also, avoid mixing modifiers incorrectly, for example, @keyup.enter.shift means Enter + Shift must be pressed together.
<!-- Wrong: key modifier on click event --> <button @click.enter="submit">Submit</button> <!-- Right: key modifier on keyup event --> <input @keyup.enter="submit">
Quick Reference
| Key Modifier | Description |
|---|---|
| enter | Triggers on Enter key |
| esc | Triggers on Escape key |
| space | Triggers on Spacebar |
| tab | Triggers on Tab key |
| up | Triggers on Up arrow key |
| down | Triggers on Down arrow key |
| left | Triggers on Left arrow key |
| right | Triggers on Right arrow key |
| .exact | Requires exact modifier keys (Ctrl, Shift, Alt, Meta) |
| .ctrl | Requires Ctrl key pressed |
| .shift | Requires Shift key pressed |
| .alt | Requires Alt key pressed |
| .meta | Requires Meta key pressed (Command on Mac) |