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, like ref and watch, has to be in the import line.
  • 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 in localStorage, 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 as push() or item.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 of review. Show it in the paragraph with the class left instead of the 200, and when it's below 0, give the paragraph the class over too, which makes it red.

  2. Save the review in localStorage under the key review whenever it changes, and read it when the app starts, so that a draft stays after Run.