Jump to Categories

Slots

You can pass content to a component using a slot

Basic Slot

Outputting a profile component

<profile url="/profile">
  Shane Prendergast
</profile>

Within the actual profile component (profile.vue)

<a v-bind:href="url">
  <slot></slot>
</a>

Outputs

<a href="/profile">
  Shane Prendergast
</a>

Slots can contain any code, including HTML and other components. If no <slot> is defined, any content passed into the component would be discarded.

Named Slots

Profile component (profile.vue)

<div>

  <div class="profile__name">
    <slot name="name"></slot>
  </div>

  <slot></slot>

  <div class="profile__contact">
    <slot name="contact"></slot>
  </div>

</div>

Using the profile card component with the slots, notice how you can either use <template> or add it to a normal HTML element.

<profile>
	
  <template slot="name">
    <h1>Joe Bloggs</h1>
  </template>

  <p>This copy here will go into the empy slot I made</p>
  <p>E.g it could be a description</p>

  <p slot="contact">email: email@email.com</p>

</profile>

Outputs

<div>

  <div class="profile__name">
    <h1>Joe Bloggs</h1>
  </div>

  <p>This copy here will go into the empy slot I made</p>
  <p>E.g it could be a description</p>

  <div class="profile__contact">
    <p slot="contact">email: email@email.com</p>
  </div>

</div>

Scoped Slots

"Everything in the parent template is compiled in parent scope; everything in the child template is compiled in the child scope."

The following url property is not accessible, but you can bind any data in a scoped slot.

Imagine the following List.vue component

<ul>

  <li v-for="item in list">
    <slot v-bind:todo="item">
    <!-- the following is for if the template is empty, fallback -->
    { { todo.text } }
    </slot>
  </li>

</ul>

Then outputting a list in a parent component, adding extra custom tick for this particular list.

<list :list="list">

  <template slot-scope="slotProps">
    <span v-if="slotProps.item.isComplete"></span>
    
  </template>

<list>

References

Component slots - Vue.js
Understanding scoped slots in Vue.js - Corebuild