Episode 15 of 44

Intro to Components

Understand Vue components — reusable, self-contained pieces of UI with their own data, template, and logic.

Intro to Components

Components are reusable building blocks for Vue applications. Each component is a self-contained unit with its own template, data, and methods. Instead of one massive Vue instance, you compose your app from small, focused components.

Registering a Component

Vue.component('greeting', {
    template: '<p>Hello, {{ name }}! <button @click="changeName">Change</button></p>',
    data() {
        return {
            name: 'Vue'
        };
    },
    methods: {
        changeName() {
            this.name = 'World';
        }
    }
});

Using the Component

<div id="app">
    <greeting></greeting>
    <greeting></greeting>
</div>

Each <greeting> tag creates an independent instance of the component. They have their own data — clicking "Change" in one does not affect the other.

Why data Must Be a Function

// WRONG — shared data across all instances
data: { name: 'Vue' }

// CORRECT — each instance gets its own copy
data() {
    return { name: 'Vue' };
}

In components, data must be a function that returns an object. If it were a plain object, all instances would share the same data — changing one would change them all.

Component Structure

PropertyPurpose
templateThe HTML template for the component
data()A function that returns the component's reactive data
methodsFunctions available to the component
computedCached derived values
propsData passed from the parent component (covered later)

Key Takeaways

  • Components are reusable UI building blocks registered with Vue.component()
  • Each component instance has its own independent data, methods, and computed properties
  • data must be a function in components — returning a new object for each instance
  • Use components as custom HTML tags: <greeting></greeting>