Advanced Vue 3: Scoped Slots Explained

Master scoped slots in Vue 3 for powerful component composition and flexibility.

Scoped slots are a powerful feature in Vue that allow a child component to expose part of its data or methods to the parent, giving the parent more control over rendering.

What Are Scoped Slots?

A scoped slot is a slot that receives data from the child component. This is useful for reusable components like lists, tables, or cards where the parent needs to customize part of the rendering.

Basic Example

ChildComponent.vue

<template>
  <slot :item="item"></slot>
</template>

<script setup>
const item = { name: 'Vue', type: 'Framework' }
</script>

ParentComponent.vue

<ChildComponent v-slot="slotProps">
  <div>
    Name: {{ slotProps.item.name }}<br>
    Type: {{ slotProps.item.type }}
  </div>
</ChildComponent>

Named Scoped Slots

You can have multiple named slots, each with its own scope:

<template>
  <slot name="header" :title="title"></slot>
  <slot :content="content"></slot>
</template>

Shorthand Syntax

Vue 3 supports the v-slot directive shorthand:

<MyComponent v-slot:default="slotProps">
  <!-- use slotProps here -->
</MyComponent>

Or simply:

<MyComponent v-slot="slotProps">
  <!-- use slotProps here -->
</MyComponent>

Best Practices

  • Use scoped slots for maximum flexibility in reusable components
  • Document the slot props your component provides

In the next post, we’ll cover the latest advancements in Vue 3, including the Composition API and Suspense.