Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 87 ยท Practice and Review

Practice Exercises with Solutions

Twelve Vue 3 exercises on reactivity, components, forms and composables, each with a hint and a live, runnable solution. Try them yourself first, then compare.

Reading about Vue is not the same as writing it. These twelve exercises turn the lessons into muscle memory. They are grouped into four sets of three: reactivity, components, forms and composables. Each exercise has a short brief and a hint, and each set ends with a complete, runnable solution.

How to get the most out of them: read one brief, close your eyes on the solution, and build your own version in a TryIt or on your computer. Only then open the solution and compare. If your version behaves the same but looks different, that is fine; there is rarely one right way. If it behaves differently, find out why, because that gap is where you learn.

All solutions load Vue from a CDN and use template strings, as explained in Ways to Use Vue. In a .vue file the logic and templates would be identical.

flowchart LR
    R["Set 1<br/>Reactivity"] --> C["Set 2<br/>Components"]
    C --> F["Set 3<br/>Forms"]
    F --> K["Set 4<br/>Composables"]

The sets build on each other: state first, then components that share it, then forms, then reusable logic.

Set 1: reactivity

Topics: ref, computed (including writable ones) and watch.

Exercise 1: temperature converter. Show two number inputs, Celsius and Fahrenheit. Typing in either one must update the other, with values rounded to whole numbers. Hint: keep one ref (Celsius) and make Fahrenheit a writable computed property with a getter and a setter. Two refs kept in sync by hand would be a bug waiting to happen.

Exercise 2: character counter. A text box with a limit of 30 characters. Show how many characters remain. When the text goes over the limit, show the counter in red and say "too long". Hint: remaining is a computed value; the red colour is a class binding.

Exercise 3: value history. A counter with + and - buttons. Below it, show the last five values the counter has had (oldest to newest, starting from the first change). Hint: this is a side effect that depends on a change over time, so use watch. Create a new array each time rather than mutating the old one, and keep only the last five with slice(-5).

Solutions: set 1, reactivity

What to check in your own solution:

  • In exercise 1, typing 212 in the Fahrenheit box sets Celsius to 100, and the Fahrenheit box then shows 212 again because it is computed from Celsius. The rounding means a round trip is not always exact, which is a good reminder that the stored value (Celsius) is the truth.
  • In exercise 2, remaining is never assigned. The template turns the negative number into a message.
  • In exercise 3, the history is empty until the first change, because watch does not run for the initial value unless you pass immediate: true. After six clicks on + the list reads 2, 3, 4, 5, 6.

Set 2: components

Topics: props, emits, v-model on components and slots.

Exercise 4: star rating. Build a StarRating component that works with v-model, shows five stars, and sets the rating when a star is clicked. The parent should be able to show the current value. Hint: a component v-model is a prop named modelValue plus an event named update:modelValue. Use buttons, not clickable spans, so the stars work from the keyboard.

Exercise 5: accordion panel. A Panel component with a title prop and a default slot. Clicking the title shows or hides the content. Hint: the open state belongs inside the panel, since the parent does not care. Use aria-expanded on the button.

Exercise 6: dismissible alert. An AlertBox component with a type prop (info or warning), a named slot title with the fallback text "Notice", a default slot for the message and a close button that emits close. The parent removes the alert when it receives the event. Hint: <slot name="title">Notice</slot> gives fallback content.

Solutions: set 2, components

Compare with your version:

  • StarRating never changes its own value. It only emits the new number, and the parent's ref feeds it back down. That is what makes it work with v-model, with a store, or with a read-only display.
  • Panel keeps open inside because no one else needs it. State that only one component cares about should stay local (designing components).
  • In AlertBox, the first alert has no title, so the fallback "Notice" shows. The second passes a title through <template #title>. Using v-if on a slot template, as done here, is allowed and is how you pass a slot only sometimes.

Set 3: forms

Topics: v-model, building forms and validation.

Exercise 7: sign-up form. Fields: email, password and "confirm password". Rules: the email must contain @, the password needs at least 8 characters, and the confirmation must match. Show each error only after the first submit attempt. A valid submit prints the data on the page (never the password). Hint: errors and valid are computed; submitted is a ref; use @submit.prevent.

Exercise 8: dependent selects. A country select and a city select. The city options depend on the chosen country, and changing the country must clear the city. Hint: a computed list of cities and a watcher on the country that resets the city.

Exercise 9: select all. A list of three checkboxes plus a "Select all" box on top. "Select all" is checked when every item is, and shows the indeterminate look when only some are. Clicking it checks or unchecks everything. Hint: a writable computed for "all", and a second computed for "some but not all".

Solutions: set 3, forms

Notes for comparing:

  • In exercise 7 the password is never part of what is "sent". Whatever you print or log should leave secrets out, even in a demo. Press the button on an empty form to see the email and password errors (the confirmation matches an empty password, so it is fine until you type something in the password box), then fix one field at a time and watch each message disappear.
  • Exercise 8 needs the watcher because the city list is derived but the selected city is state: when the list changes, the old selection may no longer be valid. Choose Peru, then Cusco, then switch to Japan and the city resets.
  • In exercise 9 the "Select all" box has no state of its own. It is a view of the three items, so it can never disagree with them.

Set 4: composables

Topics: composables and composable patterns.

Exercise 10: useToggle. A function useToggle(initial) that returns a boolean ref and toggle / set functions. Use it for a "show details" switch.

Exercise 11: useCounter with limits. useCounter({ start, min, max }) returns count, increment, decrement, reset, and two computed flags atMin and atMax. Buttons should disable at the limits. Hint: clamp inside the actions, so the rule cannot be bypassed from the template.

Exercise 12: useDebounce. useDebounce(source, delay) returns a ref that follows source only after it has stopped changing for delay milliseconds. Use it to show what a search box would send to a server. Hint: a watcher, setTimeout and clearTimeout, and onScopeDispose to clear a pending timer when the component goes away.

Solutions: set 4, composables

Look at how the pieces are shaped:

  • Each composable returns refs and functions, never unwrapped values, so the caller can keep them reactive. Here the template reads details.on, because details is a plain object holding a ref; if you want a bare on in the template, return { ...details } from setup, or destructure into constants.
  • useCounter clamps inside every action. Disabling the buttons is a courtesy; the real rule lives in the function.
  • useDebounce accepts a ref or a getter (toValue), so useDebounce(() => props.query) works too. Type fast and the lower line waits; stop for 400 ms and it catches up.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the temperature converter, why is Fahrenheit a writable computed property instead of a second ref?

    Two refs kept equal by hand can drift apart. A writable computed derives one value from the other and routes edits back to the source.
  2. 2. What does a component that supports v-model need?

    In Vue 3, v-model on a component expands to :modelValue and @update:modelValue. The child never changes the value itself; it emits the new one.
  3. 3. Why does the city select need a watcher on the country?

    The list of cities is derived, but the chosen city is stored. When the country changes, the old city may not exist in the new list, so a side effect clears it.
  4. 4. Why does useDebounce call onScopeDispose?

    A timer started by the composable could fire after the component is gone. Registering cleanup with onScopeDispose clears it at the right moment.

Summary

  • Derive values with computed (including writable ones) and use watch only for side effects over time.
  • Components own the state only they care about; shared values go down as props and changes go up as events (update:modelValue for v-model).
  • Show validation errors computed from the form, usually after the first submit attempt, and keep secrets out of any output.
  • Composables return refs and functions, accept refs or getters via toValue, enforce rules inside actions and clean up with onScopeDispose.
  • After solving an exercise, change its requirements and extend it; that is how practice sticks.

Next: avoid the traps that catch everyone in Common Mistakes.