Slots & Content Distribution
Slots allow child components to define placeholders, letting parent components inject custom HTML templates into those layouts dynamically.
1 Named and Scoped slots
Vue supports three types of slots for content distribution:
- Default Slots (<slot>): A single, unnamed placeholder slot that renders any content passed inside the child component tags.
- Named Slots: Toggles content into specific slots defined by name attributes:
<slot name="header"></slot>. - Scoped Slots: Pass reactive data from the child component back up to the parent template, letting the parent customize how the data is styled.
2 Card Slot Component Setup
Let's check how to construct a component with named slots:
Vue — Card Slot Component
<template>
<div class="box-card">
<header class="box-header">
<!-- Named slot -->
<slot name="title">Default Title</slot>
</header>
<main class="box-body">
<!-- Default slot -->
<slot></slot>
</main>
</div>
</template>
Parents can project custom templates into these slots using the v-slot or # directive:
HTML — Parent Slots Usage
<app-card>
<!-- Project into named title slot -->
<template #title>
<h2>Dynamic Product Details</h2>
</template>
<!-- Project into default slot -->
<p>This content is projected into the card main body.</p>
</app-card>
3 Code Challenge
Challenge: Write a child list component that uses scoped slots to pass individual list items back up to a parent component, allowing the parent to style each item dynamically.