Your Own Habits
Five suggestions are a start, but the tracker should hold your own habits too. Under the list comes a form with a text field and an Add button, built as in the lesson Forms:
<form @submit.prevent="addHabit">
<input v-model.trim="newName" placeholder="New habit">
<button>Add</button>
</form>
<p v-if="nameError" class="error">{{ nameError }}</p>
v-model.trim keeps what you type in the ref newName, without spaces at the start and the end. The form is sent by its button or by pressing Enter in the field, and .prevent keeps the browser from loading the page again, so that addHabit can do the work:
function addHabit() {
if (newName.value === "") {
nameError.value = "Write a name for the habit.";
return;
}
habits.value.push({
id: Date.now(),
name: newName.value,
icon: "⭐",
done: false,
});
newName.value = "";
nameError.value = "";
}
A new habit needs an id that no other habit has, for :key and for toggle(). As in the budget tracker, Date.now() gives one: the number of milliseconds since the start of 1970, which is different every time you click Add. A new habit gets a star as its icon, and it isn't done yet.
Thanks to .trim, a name made only of spaces becomes "", so the function shows an error instead of adding an empty habit, and return ends it. When the name is fine, the function adds the habit and clears the error, and the field too: newName becomes "", and v-model empties the field with it.
Instructions
- 1
Add the refs
newNameandnameError(bothref("")) and the functionaddHabit()from above, for now without theifat its start. In the template, put the form and the paragraph under the list, inside<template v-else>. Add a habit: it appears at the end of the list, and the field is empty again. - 2
Add the
ifto the start ofaddHabit(). Click Add with an empty field: a red message appears, and no habit is added. Add a real habit, and the message disappears.