Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 87 ยท Projects

Project: Todo App

Build a complete Vue 3 todo app in three live stages: list state with v-model, computed filters and counters, then components, inline editing and a useTodos composable.

A todo list is the classic first Vue project because it contains, in miniature, almost everything real apps do: a list of items, a form, user events, filtering, editing and rules about how data may change. It is small enough to finish in one sitting and big enough to make you decide where state lives and which values you store.

We will build it in three stages. Every stage is a complete program you can run and edit, and each one fixes a weakness in the one before. Along the way you will practise ref, v-for, v-model, computed properties, props and emits and composables. If one of those feels shaky, skim the linked lesson first.

The plan

Before writing code, decide what the data is and what the screen shows.

  • A todo has an id, a title and a done flag.
  • The app holds a list of todos, the text being typed and the current filter (All, Active or Done).
  • The screen shows a form, the visible list, a count of remaining items and a few buttons.

The rule that keeps small apps tidy is to store the minimum. The visible list and the number of remaining items can always be calculated from todos and filter, so they will be computed properties and never separate state.

flowchart LR
    S["State<br/>todos, draft, filter"] --> C["Computed<br/>visibleTodos, remaining"]
    C --> T["Template<br/>list, counter, buttons"]
    T -- "events: add, toggle, remove" --> A["Actions<br/>change todos"]
    A --> S

One-way flow: state feeds computed values, the template shows them, and events call actions that change the state. Nothing derived is ever stored.

All the examples load Vue from a CDN with a module import and use a template string, because the lesson runner has no build step. Everything here works the same way in a .vue file (see single-file components).

Stage 1: add, toggle and delete

Start with the smallest thing that works: a list in a ref, a text box bound with v-model, and three operations.

Stage 1: add, toggle and delete

Read the decisions that matter:

  1. Deep reactivity. todos.value.push(...) works because a ref holding an array wraps it in a reactive proxy. The checkbox can even bind v-model="todo.done" directly to a property of an item, and Vue notices.
  2. Stable ids as keys. Each todo gets an id that never changes, so :key="todo.id" lets Vue keep the right checkbox with the right item after deletes. An index would not survive removal (why keys matter).
  3. .trim() before saving. The input accepts anything, so the action validates. Rules belong in the action, not in the template.
  4. nextId is a plain variable. Nothing on screen shows it, so it needs no reactivity.

The weakness: the screen has no filter or counter, and all the logic lives in one big setup. Let us add derived data first.

Stage 2: computed filters and counters

Add a filter ref and two computed properties. A computed value is cached and recalculated only when the refs it reads change (computed), which is exactly what derived data needs.

Stage 2: filters and a counter

Notice what is not here: no code that updates the counter after a change. Tick a checkbox and remaining recomputes by itself, the list re-filters and the "Clear completed" button appears. That is the payoff of storing the minimum.

Two details are easy to miss:

  • When the filter is done and you untick an item, it disappears at once, because visibleTodos depends on done. This is correct behaviour, and it is a nice sign that the filter is derived rather than stored.
  • visibleTodos returns todos.value itself for "all". A computed value should not mutate what it reads; returning it unchanged is fine, but do not call .sort() on it, because sort changes the array in place. Use [...todos.value].sort(...).

Stage 3: components, editing and a composable

The app now works, but setup mixes data rules with view code and every row is inline. We will split it three ways:

flowchart TD
    App["App<br/>uses useTodos()"] --> Form["AddTodoForm<br/>owns the typed text"]
    App --> List["TodoItem x N<br/>owns: am I being edited?"]
    App --> Footer["Footer buttons<br/>filter, clear completed"]
    List -- "emits toggle, remove, rename" --> App

State that several parts need (the todos) stays in the top component. State only one part cares about (the draft text, the edit text) lives inside that part.

  • useTodos() is a composable: a function that owns the todos, the filter, the computed values and every action, and returns them.
  • AddTodoForm owns the text being typed and emits add with a clean title.
  • TodoItem receives one todo as a prop and emits events instead of modifying it. A child must not mutate its props (props, emits). It also owns the small editing state: double-click the title to edit, press Enter to save and Escape to cancel.
Stage 3: components, editing and useTodos

The behaviour is identical to stage 2, except that you can now rename items, and the code is split along responsibilities. Compare how the pieces talk:

  • Data moves down as props (:todo="todo").
  • Events move up with $emit, and the parent decides what they mean.
  • useTodos has no idea a screen exists. You could call it from a test, or reuse it in another page, which is the main reason to extract a composable (testing composables).

One subtle point is @blur="save" on the edit box. Pressing Enter or Escape hides the input, and some browsers fire a blur event when a focused element is removed. Without protection, Escape would cancel and then the blur would save the half-typed text anyway. That is why save starts with if (!editing.value) return;: once an edit has ended, a late blur does nothing.

Saving between visits

A real todo app remembers its list. The runner's sandbox has no localStorage, so this part is read-only, but the idea is a single watch:

JavaScript
import { watch } from "vue";

const KEY = "todos-v1";

function load() {
  try {
    return JSON.parse(localStorage.getItem(KEY)) ?? [];
  } catch {
    return [];
  }
}

const todos = ref(load());

watch(todos, (value) => {
  localStorage.setItem(KEY, JSON.stringify(value));
}, { deep: true });

Three details deserve attention. deep: true is needed because ticking a checkbox changes a property of an item, not the array itself (watch). The try/catch guards against corrupt or blocked storage. And the key has a version suffix so you can change the data shape later without crashing on old saved data.

Ideas to extend it

  • Show a "Remove all" button only after a confirmation step, using a ref for the pending state.
  • Move useTodos to its own module and share one instance between two pages (simple store).
  • Add due dates and a computed list sorted by date, remembering to copy the array before sorting.
  • Add a v-memo or virtual list only if a measured problem appears with thousands of items (performance).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are visibleTodos and remaining computed properties instead of refs updated by the actions?

    Derived data should be calculated from the minimal state. Updating a second copy by hand creates two sources of truth that can disagree.
  2. 2. Why does TodoItem emit 'toggle' instead of changing todo.done itself?

    Props flow one way. The parent owns the todos and the child only reports what the user did, which keeps every change in one place (useTodos).
  3. 3. Which key is best for the v-for over todos?

    A stable id lets Vue match items after adds, deletes and filtering. Indexes shift, titles may repeat, and random keys destroy and recreate every element.
  4. 4. In the persistence snippet, why is watch(todos, ..., { deep: true }) needed?

    A watch on a ref triggers when .value is replaced. Changes inside the nested objects need deep: true (or watching a getter that reads what you need).

Summary

  • Decide the data and the screen first, and store only the minimum state; calculate everything else with computed.
  • Use stable ids as v-for keys and validate input inside actions.
  • Split a growing app by responsibility: components for views, a composable for state and rules.
  • Data goes down as props, events go up as emits; children never mutate props.
  • Persistence is one deep watch plus a safe loader (shown read-only here because the sandbox has no storage).

Next, a project that talks to a server: Project: Weather Dashboard.