Summary

In this lesson, you learned that:

  • A component has a lifecycle: it's created (its <script setup> runs), mounted (its elements are put on the page), updated (after each change of its state) and unmounted (removed from the page, for example by v-if, and its state with it).
  • Lifecycle hooks run your code at these moments: onMounted(() => { … }), onUpdated() and onUnmounted(), imported from "vue" and called at the top of <script setup>.
  • Data from a file is loaded in onMounted, with an async function, fetch() and response.json(). With a ref such as loading, the template shows Loading… in the meantime. Never put await at the top of <script setup>: the component then shows nothing.
  • response.ok is false when the server answered with an error, such as 404 Not Found for a wrong file name. Check it, and show an error message instead of the data.
  • What a component starts, it stops: an interval started in onMounted is stopped in onUnmounted with clearInterval(). Otherwise, it keeps running after the component is gone.
  • A template ref gives you an element of the template: ref="search" in the template and const search = useTemplateRef("search"); in the script. search.value is the element once the component is mounted, and null before.
  • What's saved in localStorage is read when the ref is created, because it answers at once, and watch saves it whenever it changes.

In the next lesson, Composables, you'll take code like the loading of the menu out of components and into functions of their own, which any component can use.

But first, practice on the café's reviews page: it loads what guests wrote, puts the cursor in the field for your own review, and keeps what you've written, even when you close the page.

Instructions

  1. In onMounted, load reviews.json into reviews, so that the list shows each review like Anna: The best carrot cake in town. While the reviews are loading, show <p>Loading…</p> instead of the list.

  2. When the page opens, put the cursor in the text field for your review, with a template ref.

  3. Keep the draft: whenever the text in the field changes, save it in localStorage under the key draft, and when the app starts, start draft with what's saved. It's text already, so it doesn't need JSON. Try it: write something and click Run.