Vue Slots

🧩 Vue Slots

In Vue.js, slots allow a parent component to pass HTML content into a child component.

They make components flexible, reusable, and layout-friendly.


 What are Vue Slots?

Slots act as placeholders inside a child component where parent-provided content is rendered.

👉 Think of slots as:

“This part of the component will be filled by the parent.”


 Default Slot (Basic Slot)

🧩 Child Component

<template>
<div class="card">
<slot></slot>
</div>
</template>

🧩 Parent Component

<Card>
<h3>User Profile</h3>
<p>This content goes into the slot</p>
</Card>

✔ Everything inside <Card>...</Card> is injected into <slot>


 Slot with Fallback Content

Displayed when no content is passed.

<slot>
<p>No content provided</p>
</slot>

 Named Slots

Used when a component has multiple content areas.

🧩 Child Component

<template>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main><footer>
<slot name=”footer”></slot>
</footer>
</template>

🧩 Parent Component

<Card>
<template #header>
<h2>Profile</h2>
</template>
<p>Main content goes here</p><template #footer>
<button>Save</button>
</template>
</Card>

#header and #footer map to named slots
✔ Default slot used for main content


 Scoped Slots (Slot Props)

Allow the child to send data to the parent slot.

🧩 Child Component

<template>
<slot :user="user"></slot>
</template>
<script>
export default {
data() {
return {
user: { name: “Sanjit”, age: 25 }
}
}
}
</script>

🧩 Parent Component

<UserCard v-slot="{ user }">
<h3>{{ user.name }}</h3>
<p>Age: {{ user.age }}</p>
</UserCard>

✔ Parent can access child data safely


 Scoped Named Slots

<slot name="item" :data="item"></slot>
<template #item="{ data }">
{{ data.title }}
</template>

 Slots vs Props (Important ⚠️)

Feature Slots Props
Purpose Pass HTML/UI Pass data
Direction Parent → Child Parent → Child
Flexibility High Medium
Use case Layout & structure Configuration

✔ Props → data
✔ Slots → content/layout


 Common Use Cases

  • Cards

  • Modals

  • Layouts

  • Tables

  • Lists

  • UI libraries


 Common Mistakes ❌

❌ Overusing props instead of slots
❌ Forgetting slot fallback
❌ Confusing slot scope direction
❌ Too many named slots


Best Practices ✅

✔ Use default slot for main content
✔ Use named slots for layout areas
✔ Use scoped slots for flexibility
✔ Keep slot APIs simple
✔ Document slot usage


 Summary Table

Slot Type Syntax
Default <slot />
Named <slot name="header" />
Scoped <slot :data="value" />
Named scoped <template #name="{ data }">
Fallback <slot>Default</slot>

🏁 Conclusion

Vue slots are essential for building flexible and reusable components.
They separate structure (component) from content (parent)—a key idea in scalable Vue apps.

You may also like...