Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 87 ยท Projects

Project: Notes App with Routing

Build a multi-page Vue 3 notes app: a hash router written with plain reactivity, a shared notes store, list and detail views, a validated create and edit form, and a 404 page.

Most real Vue applications are single-page applications: the browser loads one HTML page, and JavaScript swaps the visible "page" when the address changes. Users still get bookmarkable URLs, a working back button and distinct views for a list, a detail page and a form. The piece of software that connects the address to the views is a router.

In a project built with a bundler you would use the official Vue Router (Vue Router basics). The lesson runner has no npm packages, so here you build the same ideas from scratch with plain Vue reactivity and the #/path part of the URL (hash routing, as in Build a Tiny Hash Router). That is not a handicap: after this project you will know exactly what Vue Router does for you.

The app is a notes manager with a list (with search), a detail page, a form to create and edit notes, and a "not found" page. You will build it in three stages: the router, the store with read-only views, and finally the forms. Building blocks: components, props, dynamic components, a simple store, form validation and computed properties.

Design first

The address #/notes/2/edit should mean "show the edit form for note 2". Three pieces of code make that work:

  1. A route table: a list of patterns (/notes/:id) and the component to show for each.
  2. A matcher that turns the current path into a component plus params ({ id: "2" }).
  3. Navigation: links that change the address, and a listener that reacts when it changes (the back button included).
flowchart LR
    A["Address bar<br/>#/notes/2/edit"] --> M["Matcher<br/>route table"]
    M --> P["params<br/>id = 2"]
    M --> C["Component<br/>EditNote"]
    P --> C
    C --> S["Notes store"]
    L["Link click or back button"] --> A

The address is the single source of truth for which page is showing. Components read params, talk to the store and never decide the page themselves.

The store is separate from the router: the router answers "what is on screen?", the store answers "what data exists?". Mixing the two is the most common source of tangled SPAs.

Stage 1: the router

The route table is an array, checked in order, first match wins. A pattern like /notes/:id is converted into a regular expression with one capture group per :name. The special pattern * matches anything and acts as the 404 page, so it must be last.

The router keeps one ref, path, with the current address. It updates that ref in two situations: when the browser fires hashchange (back button, typed address, plain links), and when your code calls navigate(). Everything else, the matched route and its params, is a computed value derived from path.

Stage 1: a hash router in 40 lines

Click around and watch the info line at the bottom: each address yields its own params. The link to /nowhere reaches the catch-all page, and the "from code" button shows that navigate() and a link do the same thing.

Points to remember:

  • Order matters. /notes/:id would swallow a path like /notes/new if it came before a more specific /notes/new route, because new looks like an id. Always put specific routes before parameterised ones.
  • Params are always strings. The path /notes/42 gives { id: "42" }. Convert with Number() when you compare with numeric ids (the store does this below).
  • The link handler calls .prevent. The plain href keeps links accessible and copyable, while our click handler avoids a page reload and works even where address changes are restricted.
  • Global registration. RouterLink is used inside other components, and a component registered locally is only visible in the template that lists it. So the app registers it once with app.component("RouterLink", RouterLink), which makes it available everywhere (components).
  • <component :is> picks which component to render from a value (dynamic components). The router's route is a computed value, so the page swaps automatically when path changes.
  • The hashchange listener here lives for the page's lifetime. Inside a component you would add it in onMounted and remove it in onUnmounted (lifecycle hooks).

Stage 2: the store and read-only views

Now give the pages real data. The store is a module-level function result that owns the notes, as in the shopping cart. It exposes a sorted list (a computed value that sorts a copy, newest first), a find(id) getter and the actions create, update and remove. A note has an id, title, body, a revision counter and a touched number that increases on every change; sorting by touched keeps the order deterministic without clocks.

The list view adds a search box. The query is local to that view, so it is a plain ref in the component and the filtered list is computed from the store and the query. The detail view looks up its note by params.id and handles the "no such note" case, which the address bar makes possible (anyone can type #/notes/999).

Stage 2: store, list with search, and detail view

Type "milk" into the search box and the list shrinks to one note; follow the "Missing note" link and you get the friendly not-found message instead of an error. Design points:

  • store.find(id) converts the string param with Number(id). Without it, "2" === 2 is false and every detail page would say "not found".
  • :key="path" on the dynamic component makes Vue recreate the page whenever the path changes, so local state (like the search text) never leaks from one address to another. Without a key, Vue would reuse the same component instance when two paths use the same component.
  • The detail view reads store.find(...) inside a computed value, so it also updates when the note itself changes, not just when the address changes.
  • The sorted list is a computed value over a copy ([...notes.value].sort(...)), because sort mutates in place and a computed value must not change state.

Stage 3: create, edit and delete

The last stage adds the forms. One NoteForm component serves both "new" and "edit": it receives an optional note prop, copies the values into a local reactive object (so typing does not change the stored note until you save), validates with a computed value and emits save.

Rules for validation, following the form validation lesson:

  • The title needs at least 3 characters after trimming.
  • The body may hold at most 200 characters, and the message shows how many you typed.
  • Errors are computed from the form. They appear only after the first submit attempt (submitted), so the user is not scolded for an empty form they have not touched yet.

The flow after saving is classic SPA behaviour: creating a note navigates to its new detail page, and editing navigates back to the detail page. Deleting asks for a second click first (a local confirming ref) and then returns to the list. New routes /notes/new and /notes/:id/edit are added to the table, with /notes/new before /notes/:id.

Stage 3: the complete notes app

Walk through the flows: open "Notes", choose "+ New note", press Save with an empty form (two things happen: nothing is saved and the title error appears), type a title and save, and you land on the new note's page. From there, edit it, then delete it with the two-step confirmation.

What each decision buys you:

  • One form, two jobs. The note prop is null for a new note. reactive({ title: props.note?.title ?? "" ... }) copies the values once, so pressing Cancel throws the edits away and the stored note is never half-changed. The :key="path" on the dynamic component guarantees a fresh copy when you navigate between edit pages.
  • Actions return what callers need. create returns the new id so the page can navigate to it. The store does not know about the router and the router does not know about the store; only the page components connect them.
  • The not-found cases are real. Anyone can type #/notes/999/edit, so every page that looks up data handles the missing case.
  • Validation is derived. errors and valid are computed from the form, never stored, so they cannot go stale.

What Vue Router adds

You now understand the core of Vue Router. The real library adds: nested routes and layouts, named routes and typed links, navigation guards (redirect when not logged in), lazy-loaded route components, scroll restoration, the HTML5 history mode (clean URLs without #, which needs server support) and query string handling. In a project with a build step you would define the same route table with createRouter and use <router-link> and <router-view>; the page components, the store and the forms from this project would not change. See Vue Router basics and advanced features.

Ideas to extend it

  • Add tags to notes and a /tags/:name route listing notes with that tag.
  • Support a query string (#/notes?q=milk) so searches are linkable.
  • Add a guard: a read-only "locked" flag that redirects /notes/:id/edit back to the detail page.
  • Persist notes with a deep watch and storage in a real app (read-only here, since the sandbox has none).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must the route '/notes/new' come before '/notes/:id' in the route table?

    The matcher checks routes in order and stops at the first match. A parameterised route accepts any single segment, so specific routes must be listed before it.
  2. 2. The address is #/notes/2. What does the matcher put in params.id, and why does the store call Number(id)?

    Values taken from a URL are always strings. Comparing '2' === 2 is false, so convert before comparing with numeric ids.
  3. 3. What is the purpose of :key="path" on the <component :is> element?

    When the key changes Vue destroys the old component and creates a new one, so state such as search text or a form copy cannot leak from one page to another.
  4. 4. Why does NoteForm copy the note into a local reactive object instead of binding inputs to the stored note?

    Binding to the stored note would change shared data on every keystroke, even for a change the user then cancels. A local copy keeps editing separate from saving.
  5. 5. Which part of this app decides which page is showing?

    The address is the single source of truth for the visible page. The router derives the matching component and params from it, and pages only react.

Summary

  • A router has three jobs: a route table with patterns, a matcher that extracts params, and navigation that changes the address and reacts to changes.
  • The current path is one ref; the matched route and its params are computed from it. <component :is> renders the matching page.
  • Order the route table from specific to general, keep a catch-all * last, and remember params are strings.
  • Keep the router (what is on screen) and the store (what data exists) separate; pages connect the two.
  • Give dynamic components a :key bound to the path so state does not leak between pages, and handle "not found" for every lookup.
  • One form component can serve both create and edit when it copies its input into local state and emits save.

Next, practise everything you have learned: Practice Exercises with Solutions.