Adding Expenses
Time for another project! This checkpoint puts the forms, computed values and watchers of the previous lessons to work, together with everything you learned before them. As in the previous checkpoint, the instructions say what the app should do, and how you write it is up to you.
The project. You're building a budget tracker for one month. You write down each expense: what it was for, how much it cost, and its category (food, transport or fun). The app adds the expenses up, shows how much of the monthly budget of €400 is left and how much went to each category, and it remembers everything in the browser. Over three exercises, you'll add expenses to a list, then work out the totals, and finally save the month.
The app. The form in App.vue is ready: a text field #what, a number field #amount, a select #category with the values food, transport and fun, and the button Add. Under the form is an empty list, #expenses. The script has only the import line; the rest is up to you.
The task. When the form is sent, the page must not reload. Keep the expenses in an array in a ref, and add each new one to the list as an item that shows what it was for, the amount and the category, for example Lunch: €12 (food). Then empty the text field and the number field; the category can stay as it is. But first, check the fields:
- When the field
#whatis empty (spaces at its start and end don't count), showEnter what you paid for. - When the amount is empty, 0 or less, show
Enter an amount greater than 0.
Show the message in a paragraph with the class error. While something is wrong, add nothing, and once an expense is added, the message goes away.
A tip: each expense needs an id for :key. Date.now() returns the number of milliseconds since the start of 1970, which is different every time you click Add, so it makes a good id: { id: Date.now(), … }. And with v-model.number, the amount is a number, or "" when the field is empty.
Instructions
- 1
When the form is sent, add the expense to the list and empty the fields.
- 2
Check the fields before adding, and say what's wrong.