Vue Components

🧩 Vue Components

In Vue.js, components are independent, reusable building blocks of the UI.

A Vue application is essentially a tree of components.


 What are Vue Components?

A Vue component is a self-contained unit that includes:

  • Template (HTML)

  • Logic (JavaScript)

  • Style (CSS)

✔ Reusable
✔ Maintainable
✔ Scalable


 Why Components are Important

Without components:

  • Code becomes messy

  • UI is hard to manage

  • Reuse is difficult

With components:

  • Clean structure

  • Easy maintenance

  • Team-friendly development


 Types of Vue Components

1️⃣ Root Component

The top-level component (usually App.vue).

<App />

2️⃣ Local Components

Used inside specific components.

import Header from './Header.vue'

export default {
components: { Header }
}


3️⃣ Global Components

Available everywhere (not recommended excessively).

app.component('MyButton', MyButton)

 Creating a Vue Component (SFC)

📄 src/components/Hello.vue

<template>
<h2>Hello {{ name }}</h2>
</template>
<script>
export default {
name: “Hello”,
data() {
return {
name: “Vue”
}
}
}
</script>

<style scoped>
h2 {
color: teal;
}
</style>


 Using a Component

<template>
<Hello />
</template>
<script>
import Hello from ‘./components/Hello.vue’

export default {
components: { Hello }
}
</script>


 Props (Passing Data to Components)

Parent → Child

<user-card :username="name" />
props: ['username']

✔ Props are read-only
✔ Used to pass dynamic data


 Emits (Child → Parent Communication)

<button @click="$emit('save')">Save</button>
<child-component @save="saveData" />

 Slots (Passing HTML Content)

<card>
<h3>Title</h3>
</card>
<slot></slot>

✔ Makes components flexible


 Component Lifecycle (Overview)

Every component goes through phases:

  • created

  • mounted

  • updated

  • unmounted

Used for:

  • API calls

  • DOM access

  • cleanup


 Component Naming Rules

✔ Use PascalCase for components
✔ Use kebab-case in templates

<MyButton />
<my-button />

 Component Folder Structure (Best Practice)

components/
├─ base/ # buttons, inputs
├─ layout/ # header, footer
└─ feature/ # domain components

 Common Mistakes ❌

❌ Mutating props directly
❌ Large components doing too much
❌ Overusing global components
❌ Tight coupling between components


 Best Practices ✅

✔ One responsibility per component
✔ Use props & emits properly
✔ Use slots for layout components
✔ Split large components
✔ Prefer Composition API for logic reuse


 Summary Table

Feature Purpose
Component UI building block
Props Parent → Child data
Emits Child → Parent events
Slots Content injection
Scoped CSS Style isolation

🏁 Conclusion

Vue components are the core of Vue development.
Mastering components means you can build clean, reusable, and scalable applications.

You may also like...