Vue 3 Slots

by John Pennock 5/23/2023

A cheat sheet with examples and snippets for Vue 3 Slots. See Vue 3 Slot blog post for more information.

Named Slots

You can have more than one slot in a component, but you have to name all others but one (the default)

<!-- <MyComponent> template -->
<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

A parent who wants to use the named component slots needs to specify the name with a #{name} or no name for default, like:

<!-- <MyParent> template -->
<BaseLayout>
  <template #header>
    <h1>Here might be a page title</h1>
  </template>

  <template #default>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>

  <template #footer>
    <p>Here's some contact info</p>
  </template>
</BaseLayout>

Scoped Slots

<!-- <MyComponent> template -->
<div>
  <slot :text="greetingMessage" :count="1"></slot>
</div>
<!-- <MyParent> template -->
<MyComponent v-slot="slotProps">
  {{ slotProps.text }} {{ slotProps.count }}
</MyComponent>

<!-- destructuring also works -->
<MyComponent v-slot="{ text, count }">
  {{ text }} {{ count }}
</MyComponent>