Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 87 ยท Projects

Project: Storefront with Pinia and Router

Build a small online store in Vue 3: a catalog store with filters and sorting, a cart store with derived totals, then routes for product, cart and checkout pages with a guard and a validated order form.

An online store is the classic "real" Vue project. It needs shared state (the cart must be visible from every page), derived values (totals, shipping, counts), several pages and a flow with rules (you cannot check out with an empty cart). Those are exactly the problems that stores and a router exist to solve, so the project is a good test of everything from the state-management and routing chapters.

We build it in two stages. Stage 1 creates the two stores and a single-page catalog with filters and a cart. Stage 2 adds routes for product details, the cart and a checkout, with a navigation guard and a validated form that ends in an order confirmation. Background: state sharing, Pinia basics, routing concepts, Vue Router basics and form validation.

The runner has neither Pinia nor Vue Router, so the examples use a four-line defineStore stand-in (one shared reactive object per store, like Pinia's setup stores) and a hand-made hash router. The store code is written exactly as it would be with real Pinia (import { defineStore } from "pinia"), and the page components would not change when you add createRouter.

Design first: two stores, one rule

flowchart LR
    CAT["Catalog store<br/>products, category, query, sort<br/>visible (computed)"] --> V1["Catalog page"]
    CART["Cart store<br/>lines: id + qty<br/>detailed, count, subtotal, shipping, total (computed)"] --> V2["Cart badge, cart page, checkout"]
    CAT -. "looks up products" .-> CART
    V1 -- "cart.add(id)" --> CART

Two stores with different jobs. The cart refers to products by id and asks the catalog for the details.

The rule that keeps the cart correct: store the minimum, derive the rest. The cart stores only { id, qty }. Names and prices come from the catalog at the moment they are needed, so a price change in the catalog shows up in the cart automatically, and there is no copy that can go stale. The subtotal, the shipping fee and the total are computed, never stored. And all money is kept as integer cents (why).

The business rules live in store actions, not in templates: quantity is limited to 1 to 10 (our "stock"), adding an existing product increases its quantity instead of adding a second line, and shipping is free from $50.

Stage 1: stores, filters and a cart

Stage 1: catalog store, cart store and a one-page shop

Add the backpack, then the bottle: the shipping line turns to "Free" once the subtotal passes $50, and the hint above it disappears. Filter to Outdoor, sort by price, search for "mug". Nothing in the cart changes, because the cart and the catalog are separate stores.

The points to take away:

  1. Filters are state, results are computed. visible depends on query, category and sort. There is no "apply filters" function to forget to call.
  2. [...list].sort(...) sorts a copy. Array.prototype.sort mutates, and mutating inside a computed property would corrupt the source list and re-trigger itself.
  3. The cart holds ids. detailed joins the lines with the catalog. If a price changes or a product is removed from the catalog, the cart follows (in a real shop you would also handle the removed-product case, here product would be undefined).
  4. Rules are in actions. The quantity cap is in add and setQty, so no page can break it.
  5. One store uses another. useCatalog() is called inside useCart's setup, never at module level (advanced Pinia).

Stage 2: pages, a guard and checkout

Now split the shop into pages. The hash router from Build a Tiny Hash Router gives us #/ (catalog), #/product/3, #/cart and #/checkout, plus a not-found page. Three things are new:

  • A header with a live cart count, shown on every page. It reads the same cart store, which is exactly why a store beats passing props through the app.
  • A navigation guard before rendering checkout: with an empty cart, redirect to the cart page. Guards decide whether a route may be shown; in real Vue Router they are router.beforeEach (advanced routing).
  • A checkout form with validation. Placing the order is an action that returns an order number, clears the cart and shows a confirmation.
Stage 2: routes, product page, cart, guarded checkout

Press Checkout with an empty cart: the guard sends you to the cart with a message. Open a product, add it, go to the cart and check out. Submit an empty form to see the three messages, fill it in and place the order. The header badge, the cart page and the checkout total all read the same store, and clearing the cart in placeOrder updates them together.

What to notice in Stage 2:

  • The stores did not change between stages, apart from one new action. Pages are thin: they read store state, call actions and render. That is the payoff of putting logic in stores.
  • The guard is a computed value (guarded) derived from the route, the cart and the last order. With real Vue Router it is router.beforeEach((to) => to.name === "checkout" && cart.count === 0 ? { name: "cart" } : true). Note that guards improve the experience, but the server must still validate an order: never rely on the client alone.
  • Validation produces an object of messages keyed by field, so each message sits under its input.
  • Order totals are taken from the store at the moment of ordering, and the order object stores a copy. Orders must not change when prices later do; this is the one place where copying data is right.
  • placeOrder stores the confirmation in the store (lastOrder). The cart is emptied at the same moment, so the guard must let a just-finished order through; keeping the result in the store (not in the page) means it survives the page being re-created.

Where to go next

  • Save the cart so it survives reloads, with a persistence plugin (advanced Pinia) and a version number in the storage key.
  • Load products from an API with loading and error states (fetching data); handle "product removed while in my cart".
  • Add stock limits per product, coupon codes (a computed discount) and tax by region.
  • Mirror the filters in the URL (#/?category=Outdoor) like the movie search project.
  • Lazy-load the checkout page with defineAsyncComponent (performance).
  • Add tests for the cart store: adding twice, the quantity cap, free shipping at exactly $50 (testing stores).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the cart store keep only { id, qty } instead of copying the product data?

    Store the minimum. If product data were copied into the cart, a price change in the catalog would leave the cart out of date.
  2. 2. Why does the filtering code sort a copy with [...list].sort(...)?

    Computed properties must not have side effects. Sorting the original array in place would change shared state.
  3. 3. What is a navigation guard for?

    A guard checks conditions such as 'is the cart empty?' or 'is the user signed in?' and can redirect elsewhere.
  4. 4. Where should the rule 'quantity cannot exceed 10' live?

    Rules in actions hold regardless of which page triggers the change. The UI can still hint (for example by disabling +).
  5. 5. Why does an order save its own copy of the total when it is placed?

    Snapshots belong in orders and invoices. Live lookups belong in carts.

Summary

  • Split state by responsibility: a catalog store (products, filters, a computed visible list) and a cart store (ids and quantities, computed totals).
  • Store the minimum and derive counts, subtotals, shipping and totals; keep money in cents.
  • Keep business rules (quantity caps, merging lines, free shipping) in store actions.
  • Use a router for pages and a guard to enforce flow rules, such as no checkout with an empty cart (and still validate on the server).
  • Validate the checkout form into an errors object, then place the order through a store action that returns the confirmation and clears the cart.
  • Thin pages and fat stores make a project easy to extend and to test.

Next: composables, filters, tables and charts together, Project: Reporting Dashboard.