0
0
VueHow-ToBeginner · 3 min read

How to Use Key Modifiers in Vue for Keyboard Events

In Vue, you use 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.

vue
<input @keyup.enter="submit" placeholder="Press Enter to submit">
Output
An input box that triggers the submit method only when Enter is pressed.
💻

Example

This example shows a Vue component with an input box that triggers different messages when Enter or Escape keys are pressed.

vue
<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>
Output
An input box that updates the message below when Enter or Escape keys are pressed.
⚠️

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.

vue
<!-- 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 ModifierDescription
enterTriggers on Enter key
escTriggers on Escape key
spaceTriggers on Spacebar
tabTriggers on Tab key
upTriggers on Up arrow key
downTriggers on Down arrow key
leftTriggers on Left arrow key
rightTriggers on Right arrow key
.exactRequires exact modifier keys (Ctrl, Shift, Alt, Meta)
.ctrlRequires Ctrl key pressed
.shiftRequires Shift key pressed
.altRequires Alt key pressed
.metaRequires Meta key pressed (Command on Mac)

Key Takeaways

Use Vue key modifiers by adding dot notation after event names like @keyup.enter to handle specific keys.
Key modifiers only work with keyboard events such as keyup and keydown, not with mouse events.
Use correct standardized key names like esc, enter, space, and arrow keys for reliable behavior.
Combine modifiers carefully; for example, @keyup.enter.shift requires both Enter and Shift keys pressed.
Use .exact modifier to require exact modifier keys without extras.