Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 87 ยท Projects

Project: Shopping Cart

Build a Vue 3 shopping cart in three live stages: products and computed totals, a shared cart store used by several components, then coupons, free shipping and animated lines.

A shopping cart is the project where Vue's design pays off. Many parts of the screen need the same data: the product list adds to it, the cart panel shows it, a badge counts it and a footer sums it. The totals depend on each other (subtotal, discount, shipping, grand total), and they must never disagree with what the user sees.

You will build it in three stages. First everything lives in one component, so you can focus on the data and the computed totals. Then you will move the cart into a shared store that several components use. Finally you will add a coupon, a free-shipping rule and animations with <Transition> and <TransitionGroup>. The building blocks are computed properties, list rendering, composables, sharing state and transitions.

Money is integers

Before any Vue code, one rule that prevents a whole class of bugs: never store money as floating-point dollars. JavaScript numbers are binary fractions, so 0.1 + 0.2 is 0.30000000000000004. Totals that are off by a hair look awful and break equality checks.

Store prices as integer cents (1250 means $12.50), do all arithmetic on integers, and convert to text only when displaying. One small helper does the formatting:

JavaScript
const money = (cents) =>
  (cents / 100).toLocaleString("en-US", { style: "currency", currency: "USD" });

When a percentage creates a fraction of a cent (10% of 3399 is 339.9), round once with Math.round and keep the result an integer.

Stage 1: products and computed totals

The catalogue is a plain array that never changes, so it needs no reactivity. The cart is a ref holding a list of lines { id, qty }. We store only ids and quantities and look up names and prices when needed, so a price can never get out of sync.

flowchart TD
    L["lines (state)<br/>id and qty"] --> I["items<br/>name, price, line total"]
    I --> C["count"]
    I --> S["subtotal"]
    S --> T["total"]

Only lines is state. Everything else is a computed value built on top of it, so adding a product updates every number automatically.

Stage 1: a cart in one component

Add a notebook twice and a pen set once and the cart reads 2 x Notebook = $25.00, 1 x Pen set = $8.99 and a subtotal of $33.99. No code ever "updates the subtotal"; it is recalculated because lines changed.

Two details are worth noticing. line.qty++ mutates an object inside the ref, which works because refs make their contents deeply reactive (ref). And items returns new objects built with the spread operator, so the template can never accidentally mutate the catalogue.

Stage 2: a shared cart store

Stage 1 works because there is one component. A real shop splits the screen: a product grid, a cart panel, a header badge. If each of them owned its own copy of the cart, they would drift apart. You could pass the cart down as props and events up through every level, but when two distant components need it, the simplest tool is a shared module that owns the state (sharing state, simple store).

flowchart LR
    Store["cart store<br/>state, getters, actions"]
    Store --- Grid["ProductCard x N<br/>calls add"]
    Store --- Panel["CartPanel<br/>reads items and total"]
    Store --- Badge["Header badge<br/>reads count"]

One store, many readers and writers. Components do not talk to each other: they all talk to the store.

A store is just a function that creates refs and computed values and returns them with some actions. We call it once at module level, so every component that imports cart gets the same instance. Design choices:

  • Actions are the only way in. Components call cart.add(id); they do not push into the list themselves. Rules (like a maximum quantity) then live in one place.
  • Getters are computed values. Totals are derived, never assigned.
  • The internal lines ref is not returned. Outside code can read items, count and subtotal, but cannot reach the state to break it.
Stage 2: components sharing one store

Click "Add to cart" and watch the badge in the header and the panel change together, although neither component knows the other exists. Three details of the code:

  • return { ...cart, money, MAX_QTY } spreads the store into the returned object. Refs and computed values that sit at the top level of what setup returns are unwrapped in the template, which is why the template can write items and count without .value. If you kept cart.items nested inside a plain object, you would see the ref itself instead of its value.
  • setQuantity calls remove when the quantity reaches zero, so the "-" button never produces a line with zero items.
  • MAX_QTY is enforced inside the store (add and setQuantity), and the disabled "+" button is only a courtesy to the user. The store is the real guard.

Module-level state is shared by everything that imports the module. That is the point in a browser, but on a server rendering many users' pages (SSR) it would leak one visitor's cart into another's. Pinia solves this with per-request stores (Pinia).

Stage 3: coupons, free shipping and animation

Now extend the store with the rules that make totals interesting. Each rule is one more computed value built on the previous one:

  1. subtotal: the sum of the line totals.
  2. discount: 10% of the subtotal when the coupon code VUE10 has been applied, rounded to whole cents.
  3. discounted: subtotal - discount.
  4. shipping: a flat $5.99, free once the discounted amount reaches $50.00 (and nothing for an empty cart).
  5. total: discounted + shipping.
  6. untilFreeShipping: how much more to spend for free shipping.

The chain is the heart of the lesson. Because each value is computed, you can change one rule (say, the discount percentage) in one line and every figure on screen stays consistent.

For motion, Vue has two built-in components (transitions, TransitionGroup). <TransitionGroup tag="ul"> animates cart lines entering and leaving and slides the others into place with the -move class; it requires a unique key on every child. A <Transition mode="out-in"> around the badge, with the count as its key, makes the number pop whenever it changes. Vue only adds and removes CSS classes at the right moments; the animation itself is plain CSS.

Stage 3: totals, coupon, free shipping and animation

Try this sequence: add a Backpack ($59.99). Shipping becomes free, because the discounted amount is at least $50.00. Apply VUE10 and the discount is $6.00 (10% of 5999 is 599.9, which rounds to 600), the discounted amount drops to $53.99 and shipping stays free. Now remove the backpack and add a notebook: the progress bar and the "more for free shipping" message return.

A few design remarks:

  • The coupon message is state, because it records what happened at one moment (a click). The discount itself is derived from the stored code. Keep that distinction in mind whenever you decide between a ref and a computed value.
  • Every number goes through money() only at the last moment, in the template.
  • The :key="count" trick on the badge is a nice use of key: a different key means "this is a different element", so Vue runs the leave and enter transitions.
  • The .list-leave-active { position: absolute } rule takes a leaving line out of the layout, so the remaining lines can slide up smoothly through the list-move class.

Ideas to extend it

  • Show a "Saved for later" list: a second array in the store and two more actions.
  • Add stock limits per product (a stock field) and make add respect them.
  • Keep a history of coupon attempts and show it in a debug panel (a watch on coupon).
  • Persist the cart with a deep watch and localStorage, as in the todo project (read-only in the sandbox).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are prices stored as integer cents?

    Binary floating point cannot represent most decimal fractions exactly. Integer cents keep the arithmetic exact, and you convert to dollars only for display.
  2. 2. In the store, why is the internal lines ref not returned from createCart?

    Exposing only getters and actions makes the store the single place where state changes. Components cannot push invalid data directly.
  3. 3. What does a different :key on the badge span cause inside <Transition mode="out-in">?

    Changing the key of an element tells Vue it is a different element. That triggers the leave and enter transitions, which is a common way to animate a changing value.
  4. 4. Which of these should be a computed property rather than state?

    The total can be calculated from the lines, the coupon and the shipping rule, so storing it would create a second source of truth. The lines and the code are inputs, and the message records an event.

Summary

  • Store money as integer cents, round once when a percentage creates fractions, and format only for display.
  • Keep the minimum state (lines of id and quantity) and build items, counts, subtotal, discount, shipping and total as a chain of computed values.
  • A store is a function returning getters (computed) and actions, called once at module level so every component shares one instance; do not expose the raw state.
  • Spread a store into what setup returns so top-level refs unwrap in templates.
  • <TransitionGroup> needs keys and a -move class for smooth reordering; a changing key inside <Transition> animates a changing value.
  • Module-level stores are shared between all users on a server, so use per-request stores (Pinia) for SSR.

Next: Project: Kanban Board.