Changes Inside an Array
The café's app should remember the whole order, too, so that a reload doesn't lose it. An array goes into localStorage as JSON text, as in the JavaScript course, so a watcher like the one for the name could do it:
watch(order, (value) => {
localStorage.setItem("order", JSON.stringify(value));
});But this watcher never runs. A watcher of a ref runs when its .value gets something new, such as order.value = []. push() doesn't put a new array into order.value; it changes the one that's already there. So does inOrder.count++, which changes an object inside the array. The page shows those changes, but a watcher doesn't look inside the array unless you ask it to. You ask with a third argument, the options, { deep: true }:
watch(
order,
(value) => {
localStorage.setItem("order", JSON.stringify(value));
},
{ deep: true },
);It's the same call, watch(order, function, options), only with each argument on its own line: that's how a call is usually written when the function isn't its last argument. Now Vue runs the function after any change inside the array, and inside the objects in it, too.
When the app starts, it reads the order back with JSON.parse(), and when nothing is saved, it starts with an empty array:
const saved = localStorage.getItem("order");
const order = ref(saved === null ? [] : JSON.parse(saved));Typical mistakes:
- Forgetting
{ deep: true }. Nothing is saved, and no error says why. - Saving without
JSON.stringify().localStoragethen holds[object Object], and when the app starts,JSON.parse()ends with aSyntaxError.
Instructions
- 1
Every time the order changes, save it in
localStorageunder the keyorder, as JSON text. Try adding items, the same one twice, too. - 2
When the app starts, read the saved order, or start with an empty one when nothing is saved. Add a few items and click Run: the order and its total stay.