Vue Components

Building reusable UI pieces

🧩 What are Vue Components?

Components are reusable building blocks in Vue applications. They encapsulate HTML, CSS, and JavaScript into self-contained pieces that can be used multiple times throughout your app, promoting code reusability and organization.


<!-- UserCard.vue -->
<template>
  <div class="card">
    <h3>{{ userName }}</h3>
    <p>{{ userEmail }}</p>
  </div>
</template>

<script setup>
const userName = 'John Doe'
const userEmail = '[email protected]'
</script>

<style scoped>
.card {
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 8px;
}
</style>
                                    

Output:

Component Benefits

♻️

Reusable

Use the same component many times

<UserCard />
<UserCard />
<UserCard />
📦

Encapsulated

Self-contained logic and styles

<style scoped>
/* Only affects this component */
</style>
🔧

Maintainable

Easy to update and debug

<!-- Change once, updates everywhere -->
<Button />
🎯

Organized

Keep code clean and structured

components/
  Header.vue
  Footer.vue

🔹 Creating a Component

Simple button component example:

<!-- MyButton.vue -->
<template>
  <button class="custom-btn">
    Click Me
  </button>
</template>

<script setup>
// Component logic here
</script>

<style scoped>
.custom-btn {
  background: #42b883;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.custom-btn:hover {
  background: #35a372;
}
</style>

Output:

🔹 Using Components

Import and use components in other files:

<!-- App.vue -->
<template>
  <div>
    <h1>My App</h1>
    <MyButton />
    <MyButton />
  </div>
</template>

<script setup>
import MyButton from './components/MyButton.vue'
</script>

Output:

My App

🔹 Component with Data

Components can have their own reactive data:

<!-- LikeButton.vue -->
<template>
  <button @click="likes++" class="like-btn">
    ❤️ {{ likes }} Likes
  </button>
</template>

<script setup>
import { ref } from 'vue'

const likes = ref(0)
</script>

<style scoped>
.like-btn {
  background: #ff6b6b;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 16px;
}
</style>

Output:

🔹 Multiple Component Instances

Each component instance has its own data:

<template>
  <div>
    <LikeButton />
    <LikeButton />
    <LikeButton />
  </div>
</template>

<script setup>
import LikeButton from './components/LikeButton.vue'
</script>

Output:

🧠 Test Your Knowledge

What is the main benefit of using components?