← Back to Vue.js Course | Chapter 4: Components | Lesson 5 of 7

Slots

Slots let a parent place its own content inside a child component's template.

In this page:

  1. Slots
Syntax
markup
<!-- child template -->
<div><slot>default content</slot></div>

<!-- parent template -->
<child-name>content to insert</child-name>

Slots

A child marks a spot with the slot element, and the parent puts content between the component tags. Named slots use v-slot:name (short #name) for several insertion points, and fallback content shows when nothing is provided.

Scoped slots let the child pass data back to the slot content.

Note: Use slots to build flexible layout components like cards and modals.

Example: Slots

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <fancy-card>
    <template #header>Profile</template>
    <p>Ada Lovelace, mathematician</p>
    <template #footer>Since 1843</template>
  </fancy-card>
  <fancy-card><p>No header or footer here</p></fancy-card>
</div>
<script>
  const app = Vue.createApp({});
  app.component("fancy-card", {
    template: `<section style="border:1px solid #999;margin:4px;padding:4px">
      <header><slot name="header">Default header</slot></header>
      <slot></slot>
      <footer><slot name="footer">Default footer</slot></footer>
    </section>`,
  });
  app.mount("#app");
</script>
</body>
</html>

<!-- Output:
Rendered: ProfileAda Lovelace, mathematicianSince 1843Default headerNo header or footer hereDefault footer
-->
Live Example
Related Topics
Common Mistakes
  1. Forgetting the slot element in the child
  2. Using the old slot attribute syntax
  3. Mixing up which scope variables are available
Chapter Summary
  • slot marks where content goes
  • Named slots use #name
  • Fallback content is supported
  • Scoped slots pass data up
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.