Learn Vue.js · 7/13

Component Composition with Slots

7 min read

Building scalable user interfaces requires creating components that are reusable. However, true reusability isn't just about changing the data a component displays; it is about changing the structure of what it displays.

Imagine you are running a custom picture frame factory. You manufacture the physical frames (the components), but your customers provide the photographs (the content). If your factory permanently glued a stock photo of a random pigeon into every single frame before shipping them out, you would quickly go out of business. You need a standard way to build the solid outer frame while leaving an empty space in the middle for whatever the customer wants to put inside.

In Vue.js, we achieve this architectural flexibility using Slots.

Let's dive into the mechanics of content distribution.


1. The Concept of Content Distribution (Slots)

The Problem

When building Vue applications, we use props to pass data from a parent component to a child component. This works perfectly for Strings, Numbers, and Booleans. However, passing complex HTML structures or entire nested components through a prop is a maintenance nightmare.

If you try to pass an entire <svg> icon and a <span> element as a string prop to a Button component, you lose syntax highlighting, event bindings, and overall readability.

The Solution

Vue implements a content distribution API inspired by the Web Components spec draft, using the <slot> element.

Definition

A slot is a designated placeholder inside a child component's template that allows the parent component to inject arbitrary HTML, text, or other Vue components into it.

How it works

When Vue compiles your templates, it replaces the <slot> tag in the child component with whatever HTML the parent component placed between the child component's opening and closing tags.

Let's look at an industry-standard example: a reusable BaseButton component.

Child Component: BaseButton.vue

html
<template>
  <button class="bg-blue-500 text-white px-4 py-2 rounded">
    <!-- The slot is the placeholder -->
    <slot></slot>
  </button>
</template>

Parent Component: App.vue

html
<template>
  <div class="p-4">
    <!-- Passing simple text -->
    <BaseButton>Submit</BaseButton>

    <!-- Passing HTML elements and icons -->
    <BaseButton>
      <svg class="w-4 h-4 inline-block mr-2" ...></svg>
      Checkout
    </BaseButton>
  </div>
</template>

Under the hood: Vue evaluates the parent's template, collects the Virtual DOM nodes destined for the slot, and passes them down to the child. The child then renders them exactly where the <slot> tag was placed.


2. Named Slots for Flexible Component Layouts

The Problem

A single <slot> is perfect for a simple button. But what happens when you build complex UI elements like a Modal, a Card, or a Page Layout? These components often require multiple distinct areas of content.

If you dump a title, a paragraph of text, and two action buttons into a single <slot>, you are essentially serving a customer soup, steak, and ice cream on one entirely flat plate. It blends into an unmanageable mess. The component loses control over where the specific pieces of content should live.

The Solution

We can give slots specific names using the name attribute. The parent component can then target these specific slots using the <template> tag combined with the v-slot directive.

Definition

A named slot is a slot element that includes a name attribute, allowing a component to expose multiple, uniquely identifiable placeholders for content injection. Slots without a name implicitly have the name "default".

How it works

Let's build a standardized BaseModal component commonly seen in enterprise dashboards.

Child Component: BaseModal.vue

html
<template>
  <div class="modal-backdrop">
    <div class="modal-content">
      
      <header class="text-xl font-bold border-b pb-2">
        <slot name="header"></slot>
      </header>

      <main class="py-4">
        <!-- The default slot for the main body -->
        <slot></slot>
      </main>

      <footer class="flex justify-end gap-2 border-t pt-2">
        <slot name="footer"></slot>
      </footer>

    </div>
  </div>
</template>

Parent Component: App.vue

html
<template>
  <BaseModal>
    <!-- Targeting the header slot using the # shorthand -->
    <template #header>
      <h2>Confirm Deletion</h2>
    </template>

    <!-- Implicit default slot content -->
    <p>Are you absolutely sure you want to delete the production database? This cannot be undone.</p>

    <!-- Targeting the footer slot -->
    <template #footer>
      <button class="bg-gray-300">Cancel</button>
      <button class="bg-red-500 text-white">Delete Everything</button>
    </template>
  </BaseModal>
</template>

Note on industry standards: You will almost exclusively see the shorthand # used instead of v-slot: in modern codebases. #header is identical to v-slot:header.


3. Fallback Content for Empty Slots

The Problem

When building shared UI libraries, you want your components to be robust out-of-the-box. If a parent component uses your component but forgets—or chooses not—to provide content for a specific slot, the layout might look broken or confusingly empty.

The Solution

You can place fallback (default) content directly inside the <slot> tags.

Definition

Fallback content is the default template markup defined inside a <slot> tag that is rendered by the browser only if the parent component does not provide any content for that specific slot.

How it works

Let's look at a generic SubmitButton. Most of the time, the button just says "Submit". We don't want developers to have to type <SubmitButton>Submit</SubmitButton> a thousand times across the codebase.

Child Component: SubmitButton.vue

html
<template>
  <button class="btn-primary">
    <!-- "Submit" is the fallback content -->
    <slot>Submit</slot>
  </button>
</template>

Parent Component Usage:

html
<template>
  <!-- Renders: <button>Submit</button> -->
  <SubmitButton />

  <!-- Renders: <button>Save Changes</button> -->
  <SubmitButton>Save Changes</SubmitButton>
</template>

If the parent provides content, the fallback is completely discarded and ignored. If the parent provides nothing, the fallback gracefully steps in to save the UI.


4. Scoped Slots: Passing Data Back to Parent Templates

The Problem

Up until now, our slots have followed a strict rule of variable scope: Templates in the parent component only have access to parent data. Templates in the child component only have access to child data.

Imagine you hire an accountant (the child component). The accountant holds all the complex mathematical formulas and financial records (the data/logic). However, you (the parent component) want to decide exactly how the final financial report is formatted and styled.

The problem is, the parent component determines the HTML layout of the slot, but the parent does not have access to the child's internal data.

The Solution

We use Scoped Slots. We can bind attributes to the <slot> element in the child component, making that data available to the parent's <template> block.

Definition

A scoped slot is a slot that exposes internal data or methods from the child component up to the parent component, allowing the parent to use that child data when rendering the slot's content.

How it works

This is an incredibly powerful pattern used heavily in industry for "Headless Components" (components that handle complex logic like data fetching or list pagination, but leave the visual rendering entirely to the parent).

Let's build a DataList component that fetches an array of users. It handles the loading states and the looping, but it lets the parent decide how each user looks.

Child Component: DataList.vue

html
<script setup>
import { ref } from 'vue'

// Internal child data
const items = ref([
  { id: 1, name: 'Alice', role: 'Admin' },
  { id: 2, name: 'Bob', role: 'User' }
])
</script>

<template>
  <ul>
    <li v-for="item in items" :key="item.id">
      <!-- We bind 'item' as a prop on the slot -->
      <slot :item="item" :index="item.id"></slot>
    </li>
  </ul>
</template>

Parent Component: App.vue

html
<template>
  <DataList>
    <!-- We capture the slot props using #default="slotProps" -->
    <!-- We can also destructure them immediately -->
    <template #default="{ item }">
      <div class="border p-2 mb-2">
        <h3 class="font-bold">{{ item.name }}</h3>
        <span class="text-sm text-gray-500">{{ item.role }}</span>
      </div>
    </template>
  </DataList>
</template>

Why is this used in the industry?

Separation of concerns. The DataList component is highly reusable because it makes no assumptions about the UI. It can be used to render a list of styled cards, a simple comma-separated text list, or a complex table—all while reusing the exact same underlying looping and data-fetching logic.


📚 References and Extra Reading

To deepen your understanding and see the official, up-to-date specifications, refer to the Vue.js documentation:

Challenge

Challenge: Build a Reusable Data Table Component

You will create a flexible and reusable DataTable.vue component that leverages named and scoped slots to render data provided by a parent component, App.vue.

DataTable.vue Requirements:

  1. Accept a prop named data, which will be an array of objects.
  2. The component's template should contain a standard <table> with <thead>, <tbody>, and <tfoot> sections.
  3. Implement a named slot called header inside the <thead>. Provide fallback content for this slot consisting of a single table row (<tr>) with one header cell (<th>) containing the text "Default Header".
  4. Implement a named slot called footer inside the <tfoot>.
  5. Inside the <tbody>, iterate through the data prop. For each item in the array, you must use a scoped slot named row. This slot should pass both the item object and its index back to the parent component for rendering.

App.vue Requirements:

  1. Use the DataTable component you created.
  2. Pass the users array (already defined in the script) to the data prop of the DataTable component.
  3. Provide the content for the header slot. It should be a table row containing three header cells: ID, Name, and Status.
  4. Using the row scoped slot, render a table row for each user. The cells should display the user's id, name, and a status string: "Active" if user.isActive is true, and "Inactive" otherwise.
  5. Provide content for the footer slot. It should be a table row with a single cell that spans 3 columns and displays the total number of users (e.g., "Total Users: 3").

Expected result

The final rendered output in the browser should be a styled HTML table with a header, a body, and a footer.

  • Table Header: The header row (<thead>) should contain three cells (<th>) with the text ID, Name, and Status respectively.
  • Table Body: The body (<tbody>) should contain three rows (<tr>), one for each user in the users array.
    • The first row should have cells displaying 1, Alice, and Active.
    • The second row should have cells displaying 2, Bob, and Inactive.
    • The third row should have cells displaying 3, Charlie, and Active.
  • Table Footer: The footer (<tfoot>) should contain a single row with one cell (<td>) that spans three columns and contains the text Total Users: 3.
vue

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.