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?
- Reusability: Write code once, use it everywhere.
- Maintainability: If the "Like" button breaks, you fix it in one file, and it fixes everywhere.
- 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.
<!-- 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.
<!-- 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)
<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)
<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)
<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)
<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.
- Props (Down): The car chassis tells the wheel what material it is (Leather, Plastic).
- 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 โ
- Components: Break UI into chunks (
.vuefiles). - Importing: Use
<script setup>andimport MyComponent from './...'. - Props: Use
definePropsto pass data Down. Don't mutate them! - Emits: Use
defineEmitsto 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
- Official Vue Documentation (Essentials): Vue.js Component Basics
- Props in Depth: Props Usage
- Events in Depth: Component Events
- Style Guide: Vue Specific Style Guide
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:
- Accept Props: The component must be configured to accept three props from its parent:
id: ANumberrepresenting the unique identifier for the todo.text: AStringcontaining the content of the todo item.completed: ABooleanindicating if the todo is complete.
- 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 theidof 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 theidas its payload.
- Template Logic: In the template, add two buttons.
- One button, when clicked, should trigger the
toggle-completeevent. - The other button, when clicked, should trigger the
delete-itemevent.
- One button, when clicked, should trigger the
TodoList.vue (Parent Component) Requirements:
- Render Children: In the template, use the
v-fordirective to iterate over thetodosstate array. For each object in the array, render aTodoItemcomponent. - Pass Data with Props: For each rendered
TodoItem, you must pass theid,text, andcompletedproperties from the current todo object down to the child component as props. Also, ensure you bind thekeyattribute for list rendering. - Listen for Events: Listen for the
toggle-completeanddelete-itemcustom events emitted by theTodoItemcomponents. - Handle State Changes: Implement two handler functions in the script section:
- A function to handle
toggle-complete: This function will receive anidand must find the corresponding todo item in thetodosarray and invert itscompletedstatus. - A function to handle
delete-item: This function will receive anidand must remove the corresponding todo item from thetodosarray.
- A function to handle
Expected result
TodoItem.vue Solution
Your TodoItem.vue component should correctly define its props and emits. The script block should contain:
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:
<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:
<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.
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);
}