0
0
VueConceptBeginner · 3 min read

What is Scoped Slot in Vue: Simple Explanation and Example

A scoped slot in Vue is a special slot that lets a child component pass data back to the parent through the slot's scope. It allows the parent to access and use data from the child inside the slot content, making components more flexible and reusable.
⚙️

How It Works

Imagine you have a box (child component) that holds some information, and you want to let the person outside (parent component) see and use that information inside the box. A scoped slot is like a window with a label showing what’s inside. The child component provides data through this window, and the parent can look through it and decide how to display or use that data.

In Vue, the child component defines a slot and passes data as an object. The parent uses a special syntax to receive this data and can then use it inside the slot content. This makes the child component more flexible because it doesn’t decide how the data is shown; the parent does.

💻

Example

This example shows a child component that provides a message through a scoped slot. The parent receives the message and displays it inside a styled box.

vue
<!-- ChildComponent.vue -->
<template>
  <div>
    <slot :text="message"></slot>
  </div>
</template>

<script setup>
const message = 'Hello from child!'
</script>


<!-- ParentComponent.vue -->
<template>
  <ChildComponent v-slot="slotProps">
    <div style="border: 2px solid blue; padding: 10px;">
      Message: {{ slotProps.text }}
    </div>
  </ChildComponent>
</template>

<script setup>
import ChildComponent from './ChildComponent.vue'
</script>
Output
Message: Hello from child! (inside a blue bordered box with padding)
🎯

When to Use

Use scoped slots when you want a child component to provide data or behavior, but let the parent decide how to display or use it. This is helpful for building reusable components like lists, tables, or UI widgets where the content or layout varies.

For example, a table component can provide row data through scoped slots, and the parent can customize how each row looks. This keeps the table logic separate from the display details.

Key Points

  • Scoped slots let child components pass data to parents inside slot content.
  • They make components flexible and reusable by separating data from display.
  • Use v-slot with a slot props object to access data.
  • Scoped slots are useful for customizable UI components like lists and tables.

Key Takeaways

Scoped slots allow child components to share data with parents through slots.
They help build flexible and reusable components by separating data and display.
Use the v-slot directive to access scoped slot data in the parent.
Scoped slots are ideal for components needing customizable content like lists or tables.