0
0
Vueframework~30 mins

Key modifiers for keyboard events in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Key modifiers for keyboard events
📖 Scenario: You are building a simple Vue app where users can press keys with modifiers like Shift or Ctrl to trigger different messages.
🎯 Goal: Create a Vue 3 component that listens for keyboard events with key modifiers and shows different messages based on which modifier key is pressed.
📋 What You'll Learn
Create a reactive message variable to show the current message
Add a config variable for the key to listen for (e.g., 'a')
Use Vue's key modifiers in the template to detect Shift + key and Ctrl + key
Update the message based on which key modifier was used
💡 Why This Matters
🌍 Real World
Key modifiers are often used in web apps to create keyboard shortcuts and improve user experience.
💼 Career
Understanding how to handle keyboard events with modifiers is important for building accessible and interactive web interfaces.
Progress0 / 4 steps
1
Setup reactive message variable
In the <script setup> section, create a reactive variable called message initialized with an empty string ''.
Vue
Need a hint?

Use ref from Vue to create a reactive variable.

2
Add key to listen for
Add a constant called keyToListen and set it to the string 'a' inside the <script setup> section.
Vue
Need a hint?

This will help us check which key the user presses.

3
Add keyboard event handlers with key modifiers
In the <template>, add two buttons. The first button listens for Shift + keyToListen using @keydown.shift.a. The second button listens for Ctrl + keyToListen using @keydown.ctrl.a. For each button, update message.value to 'Shift + a pressed' or 'Ctrl + a pressed' respectively inside the event handler.
Vue
Need a hint?

Use Vue's key modifiers like @keydown.shift.a and update message.value inside the handler.

4
Make buttons accessible and complete
Add tabindex="0" to both buttons to make them keyboard focusable. Also add aria-label attributes describing the key combination each button listens for: "Press Shift and a key" and "Press Ctrl and a key" respectively.
Vue
Need a hint?

Adding tabindex="0" and aria-label improves accessibility.