Typing, Keys and the Mouse

After the @ can come any event that you know from addEventListener, with the same name: @input, @keydown, @mouseover and so on.

Typing. A text field gets the event input after every change of its text. Its handler reads the text from the event object, event.target.value, and keeps it in a ref:

<script setup>
import { ref } from "vue";

const name = ref("");

function updateName(event) {
    name.value = event.target.value;
}
</script>

<template>
    <input :value="name" @input="updateName">
    <p>Hello, {{ name }}!</p>
</template>

The paragraph changes with every letter typed. :value="name" goes the other way: it puts the ref into the field, so when the script changes name.value, say to "", the field changes too. In the lesson Forms, you'll meet v-model, which does both of these in one go.

Keys. @keydown comes with every key pressed. To react only to Enter, add the modifier .enter: @keydown.enter="send". Vue then calls send only when the key is Enter, so you don't need if (event.key === "Enter"). There are others, such as .esc for Escape and .space for the space bar.

The mouse. @mouseover comes when the mouse pointer moves onto an element, and @mouseleave when it leaves the element. Together, they can show something while the pointer is over an element (with const hint = ref(false); in the script):

<template>
    <p @mouseover="hint = true" @mouseleave="hint = false">Carrot Cake</p>
    <p>{{ hint ? "Made with walnuts." : "" }}</p>
</template>

Instructions

  1. When the text in the field changes (@input), put it into note, with a function updateNote(event). The counter under the field then shows how many characters you've typed: with Oat milk, it's 8 / 50.

  2. Pressing Enter in the field (@keydown.enter) sends the note: a function send() puts note into sent, and empties note. So that the field empties too, bind it to note with :value.

  3. While the mouse pointer is over the question mark, show the help: set hint to true on @mouseover, and back to false on @mouseleave.