Vue Slots

Vue Slots

Props are fantastic for passing JavaScript data (like strings or arrays) into a child component.

But what if you want to pass actual HTML markup into a child component?

To pass full HTML blocks and templates, we use a powerful feature called "Slots".


The <slot> Element

Think of a slot as a placeholder or a placeholder cavity inside your child component.

When the parent component renders the child, it injects its own HTML directly into that slot.

This allows you to create highly reusable wrapper components, like Modals, Cards, or Layouts.


Basic Slot Example

Let's create a <FancyBox> component that wraps whatever content you place inside it.

Basic Slot Injection:

<!-- Parent Component -->
<FancyBox>
  <h2>This is injected HTML!</h2>
  <p>It will be placed exactly where the slot tag is.</p>
</FancyBox>

<!-- Child Component (FancyBox.vue) --> <template> <div class="fancy-box"> <slot></slot> <!-- The parent content goes here --> </div> </template>


Fallback (Default) Content

What happens if the parent component fails to provide any HTML content?

You can specify "fallback" content directly between the <slot> tags.

This default content will be rendered only if the parent provides nothing.

Fallback Content Example:

<!-- Inside the Child Component -->
<button type="submit">
  <slot>
    Submit <!-- This shows if the parent leaves the slot empty -->
  </slot>
</button>

Render Scope

It is crucial to understand that content injected into a slot has access to the parent's data, not the child's data.

This rule is known as the "render scope".

Everything in the parent template is compiled in the parent scope. Everything in the child template is compiled in the child scope.


Exercise 1 of 2

?

What is the primary difference between Props and Slots?

Exercise 2 of 2

?

How do you define Fallback (default) content for a slot?