Slots
Content Distribution
Slots are Vue's content distribution mechanism. They allow you to compose components by passing content from parent to child, making your components flexible and reusable.
Think of slots as "holes" in your component where the parent can insert custom content.
Default Slots
The simplest form is a default slot that accepts any content:
<!-- Card.vue -->
<template>
<div class="card">
<slot />
</div>
</template>
<!-- Usage -->
<Card>
<p>This content goes into the slot!</p>
</Card>
Named Slots
When you need multiple slots, you can use named slots to organize different content areas:
<!-- Card.vue -->
<template>
<div class="card">
<header>
<slot name="header" />
</header>
<main>
<slot /> <!-- default slot -->
</main>
<footer>
<slot name="footer" />
</footer>
</div>
</template>
<!-- Usage -->
<Card>
<template #header>
<h1>Card Title</h1>
</template>
<p>Main content goes here</p>
<template #footer>
<button>Action</button>
</template>
</Card>
Scoped Slots
Scoped slots allow the child component to pass data back to the slot content:
<!-- List.vue -->
<template>
<ul>
<li v-for="item in items" :key="item.id">
<slot :item="item" />
</li>
</ul>
</template>
<!-- Usage -->
<List :items="users">
<template #default="{ item }">
<strong>{{ item.name }}</strong>
</template>
</List>
Challenge
Create a reusable Card component with three slots:
- Named slot "header" - for the card title
- Default slot - for the main content
- Named slot "footer" - for actions/buttons
In app.vue, use the Card component to create at least two different cards with different content in each slot.
Requirements for the Card component:
- Style the card with a border and padding
- The header should have a different background color
- The footer should be aligned to the right
Tip: Use <template #slotName> syntax for named slots. The default slot doesn't need a template wrapper.
If you get stuck, you can check the solution by clicking the button below.
Slots are powerful for creating flexible, reusable components. They're especially useful for layout components, modal dialogs, and any component that needs customizable content areas.