Vue Scoped Slots

Vue Scoped Slots

As discussed earlier, slot content compiled by the parent only has access to the parent's data.

But what if the parent needs to access data that is hidden inside the child component?

To solve this problem, Vue provides a brilliant feature known as "Scoped Slots".


Passing Props from Child to Parent

A scoped slot allows the child component to pass data upwards into the slot.

Inside the child component, you can bind variables directly to the <slot> element exactly like standard props.

Child Component (MyList.vue):

<template>
  <ul>
    <li v-for="item in items" :key="item.id">
      <!-- Passing 'item' data back up to the parent slot -->
      <slot :itemData="item"></slot>
    </li>
  </ul>
</template>

Receiving Props in the Parent

In the parent component, you can receive the slot data using v-slot.

You assign a variable name (like slotProps) to v-slot="slotProps".

This variable becomes a JavaScript object containing everything the child passed up!

Receiving Scoped Props Example:

<MyList v-slot="slotProps">
  <!-- Now we can use the child's data in the parent template! -->
  <span class="green">{{ slotProps.itemData.name }}</span>
</MyList>

Object Destructuring

Instead of writing slotProps.itemData.name, you can use JavaScript object destructuring to make it cleaner.

You simply extract the exact property you need directly in the v-slot declaration.

Example: v-slot="{ itemData }"

This allows you to write {{ itemData.name }} directly in the template, saving you a lot of typing.


Exercise 1 of 2

?

What limitation of standard slots do Scoped Slots solve?

Exercise 2 of 2

?

How does a child component send data up to a scoped slot?