Summary
In this lesson, you learned that:
computed(() => …)makes a computed value from other values: a total, a filtered or sorted list, a yes or a no. The function returns the value, and Vue works it out again whenever a ref that it reads changes.- In the template, you write a computed value by its name,
{{ total }}; in the script, with.value, also inside another computed value. Without.value, you get the object:[object Object]in a text, and comparisons that are never true. - A computed value can't be assigned; change what it's made from.
computed, likerefandwatch, has to be in theimportline. - A computed value is better than a function that the template calls: it reads as a value, and Vue keeps it instead of working it out again every time it renders the template.
sort()reorders the array it sorts, so sort a copy:[...menu].sort(…). watch(source, (newValue, oldValue) => { … })does something after the source, a ref or a computed value, changes: it saves the value inlocalStorage, prints it, and so on. It doesn't run when the app starts.{ deep: true }lets a watcher see changes inside an array or an object, such aspush()oritem.count++. Without it, the watcher sees only a new.value.{ immediate: true }runs the watcher once when the app starts, too.watchEffect()runs at once and watches every ref that it reads.- Computed values are for values to show, watchers for things to do.
In the next lesson, Checkpoint: Budget Tracker, you'll put all of this to work in an app of your own: a budget for a month that adds up what you spend and remembers it.
But first, a little practice: a review of the café, with a limit on its length that counts down as you type, and a draft that stays when you click Run.
Instructions
- 1
Create a computed value
left, how many of the 200 characters are left: 200 minus the length ofreview. Show it in the paragraph with the classleftinstead of the 200, and when it's below 0, give the paragraph the classovertoo, which makes it red. - 2
Save the review in
localStorageunder the keyreviewwhenever it changes, and read it when the app starts, so that a draft stays after Run.