Episode 7 of 44

Keyboard Events

Listen for keyboard events with Vue — use key modifiers to respond to specific keys like Enter, Escape, and arrow keys.

Keyboard Events

Vue provides key modifiers that let you listen for specific keys on keyboard events. Instead of checking which key was pressed inside your method, you can filter directly in the template.

Keyboard Event Listeners

<input @keyup="logKey">
<input @keydown="logKey">
<input @keypress="logKey">

Key Modifiers

<!-- Only fires when Enter is pressed -->
<input @keyup.enter="submit">

<!-- Only fires when Escape is pressed -->
<input @keyup.esc="clear">

<!-- Only fires when Tab is pressed -->
<input @keydown.tab="nextField">

Available Key Modifiers

ModifierKey
.enterEnter / Return
.tabTab
.deleteDelete and Backspace
.escEscape
.spaceSpace
.upArrow Up
.downArrow Down
.leftArrow Left
.rightArrow Right

Chaining Key Modifiers with Alt/Ctrl/Shift

<!-- Alt + Enter -->
<input @keyup.alt.enter="submit">

<!-- Ctrl + Click -->
<button @click.ctrl="selectAll">Ctrl+Click</button>

Key Takeaways

  • Key modifiers filter keyboard events by specific key: @keyup.enter
  • Common modifiers: .enter, .esc, .tab, .space, .up, .down
  • System modifiers .ctrl, .alt, .shift can be combined with keys or click events