0
0
Vueframework~5 mins

Key modifiers for keyboard events in Vue

Choose your learning style9 modes available
Introduction

Key modifiers help you easily handle specific keyboard keys in Vue events without extra code.

You want to run code only when the Enter key is pressed in an input box.
You want to detect when the Escape key is pressed to close a popup.
You want to listen for arrow keys to move a selection up or down.
You want to prevent default browser actions on certain keys like Tab.
You want to combine keys like Ctrl + S to save data.
Syntax
Vue
<element @keydown.keyModifier="handlerFunction"></element>

Replace keyModifier with the key name like enter, esc, tab, etc.

You can chain modifiers like @keydown.ctrl.enter for Ctrl + Enter.

Examples
Calls submitForm only when Enter is pressed.
Vue
<input @keydown.enter="submitForm" />
Calls closePopup when Escape key is pressed.
Vue
<div @keydown.esc="closePopup"></div>
Calls saveData when Ctrl + S is pressed and prevents default browser save dialog.
Vue
<input @keydown.ctrl.s.prevent="saveData" />
Sample Program

This Vue component listens for Enter and Escape keys on the input. It updates the message below based on which key is pressed.

Vue
<template>
  <div>
    <input
      type="text"
      placeholder="Type and press Enter"
      @keydown.enter="onEnter"
      @keydown.esc="onEscape"
    />
    <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>
OutputSuccess
Important Notes

Key names are case-insensitive and use lowercase in Vue.

Use .prevent modifier to stop default browser actions.

You can combine multiple key modifiers for complex shortcuts.

Summary

Key modifiers let you handle specific keys easily in Vue events.

Use them to run code only on keys like Enter, Escape, or combinations.

They keep your code clean and simple for keyboard interactions.