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 byv-if, and its state with it). - Lifecycle hooks run your code at these moments:
onMounted(() => { … }),onUpdated()andonUnmounted(), imported from"vue"and called at the top of<script setup>. - Data from a file is loaded in
onMounted, with anasyncfunction,fetch()andresponse.json(). With a ref such asloading, the template showsLoading…in the meantime. Never putawaitat the top of<script setup>: the component then shows nothing. response.okisfalsewhen 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
onMountedis stopped inonUnmountedwithclearInterval(). Otherwise, it keeps running after the component is gone. - A template ref gives you an element of the template:
ref="search"in the template andconst search = useTemplateRef("search");in the script.search.valueis the element once the component is mounted, andnullbefore. - What's saved in
localStorageis read when the ref is created, because it answers at once, andwatchsaves 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, loadreviews.jsonintoreviews, so that the list shows each review likeAnna: 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
localStorageunder the keydraft, and when the app starts, startdraftwith what's saved. It's text already, so it doesn't need JSON. Try it: write something and click Run.