Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 87 ยท Components

Components Basics

Learn Vue 3 components - how to define one, register it locally or globally, reuse it with independent state, follow naming rules, and use components in template-string and in-DOM apps.

A component is a reusable piece of interface with its own template, its own logic and, if it needs it, its own state. A button, a user badge, a product card and a whole page are all components. The reason to split an interface this way is the same as splitting code into functions: you name a piece once, use it in many places, and fix it in one place.

Every Vue application is a tree of components. The root component is the one you pass to createApp; it uses other components in its template, and those use others. This lesson shows how to define a component, how to make it available to a template (registration), and how several copies of one component stay independent. The next lessons add the ways components talk to each other: props, emits and slots.

flowchart TD
  App["App (root component)"] --> Header["SiteHeader"]
  App --> List["UserList"]
  List --> B1["UserBadge (Ada)"]
  List --> B2["UserBadge (Grace)"]
  List --> B3["UserBadge (Linus)"]

One root, several children. UserBadge is written once and rendered three times.

What a component is

In the Composition API world you normally write a component as a single-file component (SFC): a .vue file with a <script setup>, a <template> and optionally a <style>. The single-file components lesson explains the format. Here is a tiny one, shown read-only because the sandbox on this site has no build step:

VUE
<!-- UserBadge.vue -->
<script setup>
defineProps(["name", "role"])
</script>

<template>
  <span class="badge">{{ name }} ({{ role }})</span>
</template>

Underneath, a component is just an object that describes what to render: a template (or a render function), the props it accepts, and a setup function for its logic. A .vue file is compiled into exactly that. The runnable examples in this track write the object by hand, with the template as a string, so they work in a plain HTML page:

JavaScript
const UserBadge = {
  props: ["name", "role"],
  template: `<span class="badge">{{ name }} ({{ role }})</span>`,
};

Both forms mean the same thing. Learn the concepts with the object form here, and when you move to a build tool the .vue file is a more comfortable way of writing it.

Local registration

Defining a component does not make it usable. A template can only use a component it knows about, and you tell it with registration. The most common kind is local registration: list the component in the components option of the parent that uses it (in an SFC with <script setup> the import alone is enough).

Defining and registering a component locally

The parent lists UserBadge under components, and the template uses it like an HTML tag. The attributes name and role are passed down to the component (that is what props are). The v-for renders one component per person, and each needs a key, exactly as with ordinary elements (see list rendering).

Local registration is the default choice because it is explicit: reading a file tells you which components it depends on, and build tools can drop components nobody uses.

Global registration

If a component should be usable everywhere without listing it in each parent, register it on the application:

JavaScript
const app = createApp(Root);
app.component("StarRating", StarRating);
app.mount("#app");

app.component(name, definition) returns the app, so calls can be chained. Global registration is convenient for a handful of truly universal pieces (a base button, an icon) and is also what plugins use to ship components. Its drawbacks are real, though: a globally registered component is always part of the bundle, even if unused, and the dependency between a parent and a child is no longer visible in the parent's file. Prefer local registration and keep global for the few cases where repeating it would be silly. The plugins lesson shows how a plugin registers components for you.

Each use is a separate instance

A component is a blueprint. Every time the template uses it, Vue creates a new instance with its own state, so ten copies of a counter keep ten different numbers. This is the whole point of components: the logic is shared, the state is not.

For the object form with the Options API, data must be a function that returns a fresh object. If it were a shared object, every instance would change the same data. With setup(), each call creates new refs, so the problem does not arise.

Reuse: every instance has its own state

Click Apples twice and Plums once: the numbers differ, although all three come from the same definition. The two countdown buttons, written with data(), are separate too. The first uses setup() with ref, the second the older Options API. Both are valid; the Composition API is the style used in new code, see Composition API and script setup.

Notice that the root template here has several top-level elements. Vue 3 allows components to have more than one root node (a fragment). If you pass attributes such as class to such a component, Vue cannot decide which root gets them; fallthrough attributes covers that.

Naming components

Naming rules are partly convention and partly technical:

  • Use PascalCase for the definition and in string templates and SFCs: UserBadge. It makes custom components visually different from native elements and works in every template that Vue compiles itself.
  • Use multi-word names for your own components (UserBadge, not Badge) to avoid clashing with present or future HTML elements. The exceptions are the root App and built-ins such as Transition.
  • Use kebab-case in in-DOM templates. When the template is real HTML written inside your page (not a string or an SFC), the browser lowercases tag names before Vue sees them, so <UserBadge> would become <userbadge>. Write <user-badge> there. In a template Vue compiles itself, both spellings are accepted.
  • A component name becomes a tag name, so it cannot be a reserved HTML tag.

Component names also appear in error messages and the browser DevTools, so descriptive names help debugging.

In-DOM templates

If you mount the app on an element that already contains markup, that markup is the template. It is handy for adding a little Vue to a server-rendered page. Because the browser parses it first, three rules apply: use kebab-case tag names, always write closing tags (<user-badge></user-badge>, never <user-badge />), and expect a brief flash of raw {{ }} text before Vue starts (hide it with v-cloak).

Global registration and an in-DOM template

The page contains plain HTML tags with kebab-case names; Vue finds them in the container, matches star-rating to the globally registered StarRating, and renders three instances. The :value="4" binding passes a number (a plain value="4" would pass the string "4"; see binding attributes). The root component here has no template at all: with no template, Vue uses the content of the mount element.

Components are for reuse, and for naming

You do not need a component only when something repeats. A good reason to extract one is that a chunk of template has a name and a job: CheckoutSummary, SearchBox. Naming it makes the parent easier to read, and gives you one place to test and change it. A good reason not to extract is when a component would need a long list of props just to hand over data the parent already owns. Designing components discusses where to draw the lines.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Ten instances of the same counter component are on the page. How is their state related?

    A component is a blueprint. Every use creates a new instance with its own refs and data, which is why logic can be reused without sharing state.
  2. 2. With the Options API object form, why must data be a function?

    If data were one shared object, all instances would read and write the same data. A function returns a new object per instance.
  3. 3. Which registration style is the default recommendation, and why?

    Local registration shows which components a file uses and allows tree shaking. Global registration is best kept for a few universal components.
  4. 4. You write markup directly in the HTML page and mount Vue on it. How do you use a component called UserBadge?

    In-DOM templates are parsed by the browser, which lowercases tags and ignores self-closing syntax on custom elements. Use kebab-case with an explicit closing tag.
  5. 5. Why should your own component names have more than one word?

    HTML elements have single-word names (or hyphenated custom elements). Multi-word component names cannot collide with native elements.

Summary

  • A component is a reusable object (or .vue file) with a template, optional props and logic; an app is a tree of them.
  • Defining a component is not enough: register it locally (components option or an import in <script setup>) or globally with app.component.
  • Prefer local registration; keep global registration for a few universal components or plugins.
  • Every use creates an independent instance with its own state; data must be a function in the object form.
  • Use multi-word PascalCase names, but kebab-case with closing tags in in-DOM templates.
  • Extract a component when a piece of template has a clear name and job, not only when it repeats.

Next: Props