Learn Vue.js ยท 5/13

Component Basics: Building Blocks of Vue

7 min read

Welcome back, code artisan! ๐Ÿฅ‹ Today, we are moving away from writing everything in a single file and stepping into the real power of Vue.js: Components.

If you've ever felt the sheer existential dread of scrolling through a 3,000-line HTML file trying to find where the "Submit" button logic lives, this lesson is your therapy session. We are going to chop that monster up into cute, manageable pieces.


1. What are Components and Why Use Them? ๐Ÿงฉ

The Problem: The Monolith

Imagine you are building a social media feed. You have a "Post" card. It has an avatar, a username, an image, and a like button.
Now, imagine you need to display 50 posts.
In standard HTML, you would copy-paste that code block 50 times. If you decide to change the "Like" button color, you have to find and replace it in 50 places. That is not programming; that is manual labor, and we hate manual labor.

The Solution: Components

Definition: A Component is a reusable, self-contained instance of a UI element that encapsulates its own HTML (template), logic (script), and styling (style).

In Vue, a component effectively allows you to create your own custom HTML elements. Instead of writing <div>...</div> a hundred times, you write <SocialPost /> once, and use it wherever you want.

Why do we love them?

  1. Reusability: Write code once, use it everywhere.
  2. Maintainability: If the "Like" button breaks, you fix it in one file, and it fixes everywhere.
  3. Sanity: It keeps your code organized.

Industry Standard: In Vue, we use Single File Components (SFCs). These files end with the extension .vue. They contain the template, script, and style all in one file. It's like a bento box for your code. ๐Ÿฑ


2. Registering and Nesting Components ๐Ÿ—๏ธ

The Concept

An application is essentially a tree of components. You have a Root component (usually App.vue), and inside that, you have a Header, a Main Content area, and a Footer. Inside the Main Content, you might have a Sidebar and a Feed. Itโ€™s boxes inside boxes.

How to do it

We will focus on Local Registration using the <script setup> syntax because it is the modern industry standard. It's cleaner, faster to write, and makes you look cool.

Step 1: Create the Child Component
Let's create a file named MyButton.vue.

vue
<!-- MyButton.vue -->
<script setup>
  // Logic goes here
</script>

<template>
  <button class="fancy-btn">
    Click Me!
  </button>
</template>

<style scoped>
.fancy-btn {
  background-color: #42b883; /* Vue Green */
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>

Step 2: Import and Use in Parent
Now, let's go to App.vue (the parent) and use this button.

vue
<!-- App.vue -->
<script setup>
// In <script setup>, importing is enough to register it!
import MyButton from './MyButton.vue';
</script>

<template>
  <h1>Welcome to my App</h1>
  <p>Here is a cool button:</p>
  
  <!-- Use it like an HTML tag -->
  <MyButton />
  
  <p>I can use it again!</p>
  <MyButton />
</template>

๐Ÿค“ Funny Fact

If you were using the older Options API, you'd have to import the component AND register it in a components: {} object. It felt like filling out paperwork just to use a button. <script setup> automates this bureaucracy.

Naming Convention

  • Filenames: PascalCase (e.g., UserProfile.vue). This is standard because it matches the JavaScript class convention.
  • In Template: PascalCase (<UserProfile />) is preferred in SFCs to distinguish them from native HTML elements. HTML elements are always lower case (<div>), custom components are PascalCase.

3. Passing Data Down: Introduction to Props ๐ŸŽ

The Problem: The Clone Wars

We have a <MyButton /> component. It says "Click Me!".
But what if we want one button to say "Login" and another to say "Sign Up"?
Right now, our component is hard-coded. It's a clone. We need a way to customize it.

The Solution: Props

Definition: Props (short for Properties) are custom attributes you can register on a component. They allow a parent component to pass data down to a child component.

Rule of Thumb: Data flows down (Parent โ†’ Child).

How to use defineProps

In the child component, we must declare what props we accept.

1. The Child (UserProfile.vue)

vue
<script setup>
// We declare that this component expects a 'username' and 'age'
// defineProps is a compiler macro (no need to import it)
defineProps({
  username: String,
  age: Number,
  isPremium: Boolean
});
</script>

<template>
  <div class="card">
    <!-- We use the props just like variables -->
    <h2>User: {{ username }}</h2>
    <p>Age: {{ age }}</p>
    <p v-if="isPremium">๐ŸŒŸ Premium Member</p>
  </div>
</template>

2. The Parent (App.vue)

vue
<script setup>
import UserProfile from './UserProfile.vue';
import { ref } from 'vue';

const currentAge = ref(25);
</script>

<template>
  <!-- Passing static strings -->
  <UserProfile username="Alice" age="30" is-premium />

  <!-- Passing dynamic data with v-bind (:) -->
  <!-- Note: We use kebab-case for props in templates usually, 
       but camelCase works too. kebab-case is HTML standard. -->
  <UserProfile 
    username="Bob" 
    :age="currentAge" 
  />
</template>

โš ๏ธ Critical Rule: One-Way Data Flow

Props are read-only in the child.
If you try to do props.username = "New Name" inside the child, Vue will yell at you in the console. Itโ€™s like a parent giving a child a packed lunch. The child eats the lunch; the child does not magically transform the sandwich into a steak inside the box. If you want to change the data, the Parent must change it.


4. Emitting Events: Child to Parent Communication ๐Ÿ“ฃ

The Problem: The Silent Child

We passed data down. Great.
But what if the User clicks a "Delete Account" button inside the UserProfile component?
The UserProfile (Child) knows it was clicked, but the data lives in App.vue (Parent). The Child cannot delete the data directly (remember One-Way Data Flow).

The Child needs a way to scream, "HEY! I WAS CLICKED! DO SOMETHING!"

The Solution: Emits

Definition: Emits are custom events that a component triggers. The parent listens for these events and executes code in response.

Rule of Thumb: Events flow up (Child โ†’ Parent).

How to use defineEmits

1. The Child (ActionItem.vue)

vue
<script setup>
// 1. Define the events this component can emit
const emit = defineEmits(['increase-count']);

function handleClick() {
  console.log('Button clicked in child');
  // 2. Emit the event by name
  // We can also pass data (payload) as a second argument
  emit('increase-count', 1); 
}
</script>

<template>
  <button @click="handleClick">Add +1</button>
</template>

2. The Parent (App.vue)

vue
<script setup>
import { ref } from 'vue';
import ActionItem from './ActionItem.vue';

const count = ref(0);

// This function runs when the child yells
function handleIncrease(amount) {
  count.value += amount;
}
</script>

<template>
  <h1>Count: {{ count }}</h1>
  
  <!-- Listen to the event using @ (v-on) -->
  <!-- When 'increase-count' happens, run 'handleIncrease' -->
  <ActionItem @increase-count="handleIncrease" />
</template>

Real Life Simulation ๐ŸŽฎ

Think of a Steering Wheel component in a car.

  1. Props (Down): The car chassis tells the wheel what material it is (Leather, Plastic).
  2. Events (Up): When the driver turns the wheel, the wheel doesn't turn the car tires directly. The wheel emits a "turn" event to the steering column (Parent), which then turns the tires.

Summary Checklist โœ…

  1. Components: Break UI into chunks (.vue files).
  2. Importing: Use <script setup> and import MyComponent from './...'.
  3. Props: Use defineProps to pass data Down. Don't mutate them!
  4. Emits: Use defineEmits to send events Up.

You have just learned the alphabet of Vue architecture. Next, we start forming words and sentences (Advanced Component Logic). Grab a coffee, you earned it. โ˜•๏ธ


๐Ÿ“š Further Reading & References

Challenge

Challenge: Build a Reusable Todo List

You are tasked with creating a simple but functional Todo List application by composing two Vue components: TodoList.vue (the parent) and TodoItem.vue (the child). This will require you to manage state in the parent component and communicate between the parent and child using props and emits.

Your goal is to fill in the // TODO: sections in the provided code for both components.

TodoItem.vue (Child Component) Requirements:

  1. Accept Props: The component must be configured to accept three props from its parent:
    • id: A Number representing the unique identifier for the todo.
    • text: A String containing the content of the todo item.
    • completed: A Boolean indicating if the todo is complete.
  2. Emit Events: The component must be configured to emit two custom events up to its parent:
    • toggle-complete: This event should be emitted when the user wants to change the completion status. It must include the id of the todo item as its payload.
    • delete-item: This event should be emitted when the user wants to remove the todo. It must also include the id as its payload.
  3. Template Logic: In the template, add two buttons.
    • One button, when clicked, should trigger the toggle-complete event.
    • The other button, when clicked, should trigger the delete-item event.

TodoList.vue (Parent Component) Requirements:

  1. Render Children: In the template, use the v-for directive to iterate over the todos state array. For each object in the array, render a TodoItem component.
  2. Pass Data with Props: For each rendered TodoItem, you must pass the id, text, and completed properties from the current todo object down to the child component as props. Also, ensure you bind the key attribute for list rendering.
  3. Listen for Events: Listen for the toggle-complete and delete-item custom events emitted by the TodoItem components.
  4. Handle State Changes: Implement two handler functions in the script section:
    • A function to handle toggle-complete: This function will receive an id and must find the corresponding todo item in the todos array and invert its completed status.
    • A function to handle delete-item: This function will receive an id and must remove the corresponding todo item from the todos array.

Expected result

TodoItem.vue Solution

Your TodoItem.vue component should correctly define its props and emits. The script block should contain:

javascript
import { defineProps, defineEmits } from 'vue';

const props = defineProps({
  id: Number,
  text: String,
  completed: Boolean
});

const emit = defineEmits(['toggle-complete', 'delete-item']);

The template should include two buttons that use the $emit function (or a handler function that calls emit) to send events with the item's id as the payload:

html
<template>
  <li>
    <span :class="{ completed: completed }">
      {{ text }}
    </span>
    <div>
        <button @click="$emit('toggle-complete', id)">Toggle</button>
        <button @click="$emit('delete-item', id)">Delete</button>
    </div>
  </li>
</template>

TodoList.vue Solution

Your TodoList.vue component's template should correctly use v-for to render the TodoItem components, binding all necessary props and listening for the custom events:

html
<template>
  <div>
    <ul>
      <TodoItem
        v-for="todo in todos"
        :key="todo.id"
        :id="todo.id"
        :text="todo.text"
        :completed="todo.completed"
        @toggle-complete="handleToggle"
        @delete-item="handleDelete"
      />
    </ul>
  </div>
</template>

The script block must implement the two handler functions. handleToggle should find the item and flip its completed property. handleDelete should filter the array, creating a new array without the deleted item.

javascript
function handleToggle(id) {
  const todo = todos.value.find(item => item.id === id);
  if (todo) {
    todo.completed = !todo.completed;
  }
}

function handleDelete(id) {
  todos.value = todos.value.filter(item => item.id !== id);
}
vue

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.