In Vue.js, key modifiers are special directives that can be used to handle keyboard events with more specificity. These modifiers are often used in conjunction with event binding to capture and respond to specific key combinations.
Here are key modifiers in Vue.js in more detail:
1. .enter
- Usage: @keyup.enter, @keydown.enter
- Description: Listens for the Enter key press.
<input @keyup.enter="submitForm" />
2. .tab
- Usage: @keyup.tab, @keydown.tab
- Description: Captures the Tab key press.
<input @keyup.tab="nextField" />
3. .delete or .backspace
- Usage: @keyup.delete, @keydown.delete, @keyup.backspace, @keydown.backspace
- Description: Captures the Delete or Backspace key press.
<input @keyup.delete="deleteItem" />
4. .esc
- Usage: @keyup.esc, @keydown.esc
- Description: Captures the Escape key press.
<input @keyup.esc="cancelAction" />
5. .space
- Usage: @keyup.space, @keydown.space
- Description: Captures the Space key press.
<button @keyup.space="startAction"></button>
6. .up, .down, .left, .right
- Usage: @keyup.up, @keydown.up, @keyup.down, @keydown.down, @keyup.left, @keydown.left, @keyup.right, @keydown.right
- Description: Captures arrow key presses.
<div @keyup.up="moveUp"></div>
7. .ctrl, .alt, .shift, .meta
- Usage: @keyup.ctrl, @keydown.ctrl, @keyup.alt, @keydown.alt, @keyup.shift, @keydown.shift, @keyup.meta, @keydown.meta
- Description: Captures specific modifier key presses.
<div @keyup.ctrl="handleCtrlKey"></div>
8. .exact
- Usage: @keyup.ctrl.exact, @keyup.alt.exact, @keyup.shift.exact, @keyup.meta.exact
- Description: Requires that no other keys are pressed in conjunction with the specified key.
<div @keyup.ctrl.exact="handleCtrlKey"></div>
<template>
<div>
<input @keyup.enter="handleEnterKey" />
<button @click="submitForm" @keyup.enter="submitForm">Submit</button>
<div @keyup.ctrl.alt="handleCtrlAlt"></div>
</div>
</template>
<script>
export default {
methods: {
handleEnterKey() {
// Handle Enter key press
},
submitForm() {
// Handle form submission
},
handleCtrlAlt() {
// Handle Ctrl + Alt key press
}
}
};
</script>
In the above example, @keyup.enter is used to listen for the Enter key press on an input field, @keyup.enter is used on a button to submit a form, and @keyup.ctrl.alt is used to handle a key combination of Ctrl + Alt.
Summary
Key modifiers provide a clean and readable way to handle specific keyboard events and combinations in Vue.js applications.