Vue v-slot (Named Slots)

Vue v-slot (Named Slots)

A single, unnamed <slot> tag is great for wrapping simple content.

But what if you are building a complex layout component, like an Article with a distinct Header, Main Body, and Footer?

You will need multiple different slots. To achieve this, Vue provides Named Slots using the v-slot directive.


Creating Named Slots

Inside the child component, you can give a <slot> element a specific name using the name attribute.

This tells Vue exactly which placeholder belongs to which section.

If a slot is written without a name attribute, it implicitly has the name "default".

Child Component (Layout.vue):

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot> <!-- Implicit default slot -->
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

Injecting into Named Slots

To pass content into a specific named slot from the parent, you must use a <template> tag.

You apply the v-slot directive to the <template> tag, followed by a colon and the slot's name.

Parent Injection Example:

<Layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

<!-- Content not in a template tag goes to the default slot --> <p>A paragraph for the main content.</p>

<template v-slot:footer> <p>Here's some contact info</p> </template> </Layout>


The # Shorthand Syntax

Just like v-bind and v-on, the v-slot directive is used so frequently that it has a dedicated shorthand.

You can replace v-slot: entirely with the # symbol!

For example, v-slot:header simply becomes #header. This makes your template syntax beautifully concise.


Exercise 1 of 2

?

If a child component has a slot without a 'name' attribute, what is its implicit name?

Exercise 2 of 2

?

What is the official shorthand symbol for the v-slot directive?