Sending the Form

So far, the fields only showed what's typed. Now the customer sends the order. As in the JavaScript course, fields that belong together go into a form, and the form gets the event submit when its button is clicked, or when Enter is pressed in one of its text fields. In Vue, you handle it with @submit, on the form:

<form @submit.prevent="addOrder">
    <label for="name">Your name</label>
    <input id="name" v-model.trim="name">
    <button>Order</button>
</form>

A button in a form sends it, even without type="submit". And remember the browser's default action: when a form is sent, the browser loads the page again. A Vue app then starts over: every ref is back to its starting value, and the list of orders is empty. The modifier .prevent calls event.preventDefault() for you, before your function runs. See what happens without it: the form in this exercise has no @submit yet, so type a name, click Order, and watch the page start over.

Adding the order. The function makes an object from the refs and adds it to the array that v-for shows:

const orders = ref([]);
let nextId = 1;

function addOrder() {
    orders.value.push({ id: nextId, name: name.value, drink: drink.value });
    nextId++;
    name.value = "";
    drink.value = "";
}

Each order gets its own id for its :key, from nextId, which goes up by one after every order. nextId is a plain let, not a ref: the page never shows it, so Vue doesn't need to know when it changes. The last two lines get the form ready for the next customer: thanks to two-way binding, emptying the refs empties the fields.

Instructions

  1. When the form is sent, add the order to orders, as an object with id, name and drink, and keep the page from loading again. The list under the form shows it: Anna: Cappuccino.

  2. After adding the order, empty the name field and set the drink back to Choose a drink.