Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 87 ยท Components

Designing Components

Design Vue components that stay small and reusable. Learn single responsibility, container and presentational components, props versus slots, API design, naming and a reuse checklist.

Knowing the building blocks (props, emits, slots, v-model, provide and inject) is one skill. Knowing how to combine them into components that stay pleasant to use for years is another. A badly designed component works on day one, then collects boolean props, special cases and copy-pasted variants until nobody dares to touch it. A well designed one is small, has an obvious purpose, and reads like a tiny HTML element: you can guess how to use it.

This lesson is the capstone of the Components chapter. It does not introduce new syntax. It gives you a way of thinking: give each component one job, separate "where the data lives" from "how it looks", pick props or slots deliberately, design a small and consistent API, name things predictably and check reuse before extracting. If you know React, the ideas overlap with Component Design in React; the Vue mechanics differ, the reasoning does not.

Examples use template-string components and the full browser build of Vue 3.5.13 (with the template compiler) from jsDelivr, since the site runs no build step. In a project, each component below would be one .vue file.

One component, one job

A useful test: can you describe the component in one short sentence without the word "and"? "Shows a single to-do item" passes. "Shows the to-do list, filters it, saves it to the server and renders the page header" does not. When a component fails the test, split it.

Signs that a component is doing too much:

  • Its template is longer than one screen, or has deeply nested v-if / v-for blocks.
  • It has many props that only matter in combination ("isEditing, showEditIcon, editMode").
  • Part of the template could be named and reused on another page.
  • Testing it requires mocking half the application.

Splitting is not free: every component adds a file, a name and a prop boundary. Extract when there is a clear name for the piece, or when it repeats. Do not extract a component for every div.

Container and presentational components

A popular and practical split separates where data lives from how it looks:

  • A container (or "smart") component owns state, talks to the server or a store, and decides what happens when something occurs.
  • A presentational (or "dumb") component receives everything through props, shows it, and reports user actions with events. It has no idea where the data came from.
flowchart TB
  C["TodoApp (container)<br/>owns todos, add, toggle, remove"] -->|"props: todos"| L["TodoList (presentational)"]
  L -->|"props: todo"| I["TodoItem (presentational)"]
  I -. "emit toggle, remove" .-> L
  L -. "emit toggle, remove" .-> C

Data flows down as props, user intentions flow up as events. Only the container changes the state.

Presentational components are easy to reuse, test and preview, because they behave like pure functions of their props. The container is where the application logic is concentrated, and with the Composition API that logic can itself be moved into a composable.

The example splits a small to-do app this way. TodoItem and TodoList know nothing about how to add or remove tasks; they only render and emit. The root component owns the array.

A container with presentational children

The same pattern appears at larger scale in Project: Todo App. Do not apply it blindly: a small component that holds its own tiny bit of UI state (is this dropdown open?) is perfectly fine, and that state is not "application state".

Props or slots?

You met both in earlier lessons: Props pass data, Slots pass markup. Choosing between them is the most common API decision.

flowchart TD
  Q1{"Is it plain data or a<br/>simple choice?<br/>(text, number, size, variant)"}
  Q1 -->|"yes"| P["Use a prop"]
  Q1 -->|"no"| Q2{"Does the parent need to control<br/>markup or put components inside?"}
  Q2 -->|"yes"| Q3{"Does the child own data the<br/>parent's markup needs?"}
  Q3 -->|"yes"| SS["Use a scoped slot"]
  Q3 -->|"no"| S["Use a slot"]
  Q2 -->|"no"| P

A rough decision path. When in doubt, start with a prop; add a slot when a prop starts to need HTML.

Practical rules:

  • A prop that holds HTML (:content="'<b>hi</b>'") is a smell. Use a slot, and you avoid v-html and its security risk.
  • Many boolean props that change the layout (withIcon, withFooter, withBorder) usually want to become slots: if the parent fills the footer slot, there is a footer.
  • A prop with a closed set of values (variant="primary" | "danger") is better than ten booleans: invalid combinations become impossible.
  • Give every slot fallback content when a sensible default exists.

Designing the API

A component's API is its props, events, slots and exposed methods. Treat it like a public interface:

  1. Keep it small. Each prop is something you must document, test and support. Add one when two real call sites need it.
  2. Make the common case short. <AppAlert>Saved</AppAlert> should work with no props.
  3. Prefer strings and booleans with defaults over required complexity. Validate closed sets with a validator.
  4. Events describe what happened, not what to do. Emit dismiss, not hideMe; the parent decides the reaction.
  5. Support v-model for form-like components (v-model on Components).
  6. Let attributes fall through to the root element, so class, id and listeners just work (Fallthrough Attributes).
  7. Do not mutate props; emit an event or use a local copy (Props).

The AppAlert below follows those rules. It has a validated type prop, default content in a slot, an optional named icon slot, a dismissible flag and a dismiss event. The parent decides what dismiss means: here, it removes the alert from a list.

A small, well-shaped AppAlert

Try dismissing an alert: the component only reports the event, and the parent's list changes. The first two alerts show the "short form": no props at all, and an icon passed through a slot.

Wrapper, higher-order and functional components

Sometimes you do not build a component from scratch but wrap an existing one: a third-party date picker, your own BaseInput, or a button from a component library. The goal is to add behaviour or defaults while keeping the original usable. Three techniques cover almost every case. (Renderless components, which share logic through a scoped slot, were covered in Slots.)

Wrapper components: forward attributes and slots

A wrapper should behave as if the inner element were written directly. Three things make that happen:

  1. Attribute forwarding. Attributes that are not declared as props (placeholder, type, class, aria-label, listeners) fall through to the single root element automatically. When the root is not the element that should receive them, set inheritAttrs: false and bind $attrs yourself, as in the next demo and in Attributes and Inheritance.
  2. v-model forwarding. Accept modelValue, emit update:modelValue (component v-model).
  3. Slot forwarding. To pass a slot through to the inner component, render <slot /> inside the matching slot of the inner component.

Higher-order components

A higher-order component (HOC) is a plain function that takes a component and returns a new component with extra behaviour. The idea is familiar from React. It is rarer in Vue, because composables and slots usually do the same job more visibly, but you will meet it in libraries and it is useful to know. The wrapper renders the original with h(), passing along all attributes and slots.

Functional components

A functional component is just a function that receives props and a context ({ slots, attrs, emit }) and returns vnodes. It has no state, no lifecycle and no template of its own, so it is the lightest way to make a small presentational piece. Declare its props with a props property on the function; without it, every attribute arrives in attrs.

A wrapper, a higher-order component and a functional component

Type in the field: the type and placeholder attributes you wrote on LabeledInput end up on the inner <input>, because v-bind="$attrs" forwards them, while label and modelValue are props and never reach it. Badge is a plain function, yet it accepts a slot and a tone prop. withLoading consumes its own loading prop and hands everything else (name, the default slot) to Profile.

Prefer the simplest tool: a wrapper component for added defaults, a composable when only logic is shared, a scoped slot when the parent must control the markup. Reach for a HOC mainly when you must add the same behaviour to many components you do not own. One caveat: inheritAttrs: false with a <template> that has several root nodes means you must decide where $attrs goes, or Vue warns.

Naming conventions

Consistent names make a codebase searchable and predictable. These are the conventions of the official style guide, and they are worth following unless your team has its own:

  • Component names are multi-word and PascalCase in code (TodoItem, not Todo), so they never clash with present or future HTML elements. A common exception is App.
  • Base components (buttons, inputs, icons without business logic) share a prefix such as Base or App: BaseButton, AppAlert.
  • Single-instance components (used once per page) start with The: TheHeader, TheSidebar.
  • Tightly coupled children carry the parent's name as a prefix: TodoList, TodoListItem.
  • Props are camelCase in JavaScript and kebab-case in templates (isOpen / is-open). Template strings accept either.
  • Events are verbs in the past or a plain noun: update:modelValue, dismiss, select. Use kebab-case in templates (@item-selected).
  • Composables start with use (useMouse) and live apart from components.

More on this in Code Quality and Style.

A reuse checklist

Before you extract, copy or generalise a component, run through this list:

Question If the answer is yes
Does the same markup appear in three or more places? Extract a component. (Twice is often a coincidence.)
Does it have a clear one-sentence description? Name it after that sentence.
Can it work with only props, slots and events (no global state)? It is reusable. If not, split the data access out.
Are there more than five or six props, or boolean props that exclude each other? Replace some with slots or a variant prop.
Is only the logic shared, not the markup? Extract a composable, not a component.
Is only the look shared? Consider plain CSS classes, a base component or a design token.
Would the parent otherwise reach into the child's internals? Add a prop, event or exposed method instead (Template Refs).
Is the dependency needed by many deep descendants? Consider provide and inject.

Finally, resist designing for imaginary future uses. A component that serves two real call sites well beats one with twelve options for hypothetical ones. You can always add a prop later; removing one is a breaking change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main job of a presentational component?

    A presentational component is a function of its props that emits events. The container decides where data comes from and what actions do.
  2. 2. A component has the boolean props withHeader, withFooter and withIcon that each switch a piece of markup on. What is usually a better design?

    Named slots let the parent control the markup, and checking $slots lets the component skip empty wrappers. That replaces a pile of flags.
  3. 3. Which event name describes what happened, as recommended?

    Events should announce an occurrence and leave the reaction to the parent. dismiss does that, while the others tell the parent what to do.
  4. 4. Two pages share the same fetch-and-filter logic but display it very differently. What should you extract?

    When only logic is shared, a composable is the right tool. Each page keeps its own markup.
  5. 5. Which component name follows the style guide?

    Multi-word PascalCase names avoid clashes with HTML elements, and TodoItem also says what the component is. A single-word name like Todo or Item is too generic.

Summary

  • Give each component one job that you can describe in a sentence; split when a component grows several reasons to change.
  • Containers own state and logic; presentational components take props and emit events, which makes them easy to reuse and test.
  • Use props for data and simple choices, slots for markup, and scoped slots when the child owns the data the parent's markup needs.
  • Keep APIs small, make the common case short, validate closed sets, emit events that describe what happened, and never mutate props.
  • Follow naming conventions: multi-word PascalCase components, Base / The prefixes, use for composables.
  • Extract after the pattern repeats, choose composables for shared logic, and avoid adding options for imaginary use cases.

You now have the full toolkit for components. The next chapter looks inside them with the Composition API, starting at Composition API and script setup.