Advanced 18 min read

Slots and Composition

By the end of this lesson, you'll be able to:

  • Define a slot to accept markup from a parent component
  • Use named slots for multiple distinct insertion points
  • Distinguish composition via slots from passing data via properties

Prerequisites: "DOM Querying and Refs"

What Is a Slot?

<!-- c-card markup -->
<template>
    <div class="card">
        <slot></slot>
    </div>
</template>
<!-- used by a parent -->
<c-card>
    <p>This paragraph is placed wherever the slot appears.</p>
</c-card>

A <slot> marks a spot in a component's own template where a parent's markup gets inserted — a composition pattern, distinct from passing data through @api properties (Module 5). Instead of the parent handing the child values, the parent hands the child markup to render in a designated place.

Default and Named Slots

<!-- c-card markup -->
<template>
    <div class="card">
        <header class="card-header">
            <slot name="header"></slot>
        </header>
        <div class="card-body">
            <slot></slot>
        </div>
    </div>
</template>
<!-- used by a parent -->
<c-card>
    <h2 slot="header">Account Summary</h2>
    <p>This goes into the default (unnamed) slot.</p>
</c-card>

A component can define multiple named slots (<slot name="header">) plus one default (unnamed) slot. The parent routes content to a specific named slot using a matching slot="header" attribute; anything without a slot attribute goes to the default slot.

Why This Matters in Real Projects

Slots are what make a component like c-card genuinely reusable — the same card "shell" component can wrap completely different content in different places, without the card component needing to know anything about what it contains.

Exercise

Write the template for a c-panel component with a named "title" slot and a default slot for the body content.

Show hint

Follow the c-card pattern shown above.

JAVASCRIPT

Exercise

Challenge: explain, as a comment, how slots differ fundamentally from passing data via an @api property.

Show hint

Think about what is actually being handed to the child — a value, or markup.

JAVASCRIPT

Slots and Composition Quiz

1. What does a <slot> element allow a component to accept?

2. How does a parent route content to a specific named slot?

3. What happens to content with no slot attribute?

4. How many named slots can a single component define?

5. What makes a slot-based component like c-card genuinely reusable?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A slot lets a component accept arbitrary markup from its parent — a composition pattern fundamentally different from passing data through properties, and the mechanism behind flexible, reusable container components.