Spaces and Numbers

What customers type isn't always what they mean, and two things get in the way most often. v-model has a modifier for each: a word after a dot that changes what it does, as .enter does in @keydown.enter.

Spaces. A name typed with spaces around it, "  Anna ", goes into the ref with them. On the page, the spaces before it mostly disappear, but the one after it shows: Order for Anna . And a name of only spaces isn't "", so a check for an empty name doesn't catch it. v-model.trim puts the text into the ref without the spaces at its start and end, as trim() does:

<input v-model.trim="name">

Numbers. The value of a field is always text, and so is the value of an option: value="2" is "2", not 2. And text and numbers don't add up, as you know from the JavaScript course: 3 + "2" is "32". Here's a tip from a drop-down list, added to the price of a cappuccino:

<select v-model="tip">
    <option value="0">No tip</option>
    <option value="2">€2</option>
</select>
<p>Total: €{{ price + tip }}</p>

With const price = 3; and €2 chosen, the total is €32. v-model.number turns the value into a number before it goes into the ref, and then the total is €5:

<select v-model.number="tip">

Two more things about numbers:

  • A field with type="number" is a field for numbers, and Vue adds .number to its v-model by itself.
  • Radio buttons and checkboxes ignore .number. Give them their values with :value instead: :value="2" is the number 2, because with :, what's in the quotes is JavaScript.

Instructions

  1. Type Anna into the name field, with a few spaces before and after it, and look at the summary. Then add .trim to the field's v-model.

  2. Choose a €2 tip and look at the total. Then make the tip a number with .number.