0 day streak
javascript / intermediate
Snippet

Flexible Layouts with Scoped Slots

Scoped slots allow a child component to pass data back to its parent, enabling the parent to decide how that data should be rendered. This promotes high reusability by decoupling the logic from the presentation.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- ChildComponent.vue -->
<template>
<ul>
<li v-for="item in items" :key="item.id">
<slot :item="item" :status="item.active ? 'Active' : 'Idle'"></slot>
</li>
</ul>
</template>
<!-- ParentComponent.vue -->
<template>
<ChildComponent :items="data">
<template #default="{ item, status }">
<span>{{ item.name }} - State: {{ status }}</span>
</template>
</ChildComponent>
</template>
vue
Breakdown
1
<slot :item="item">
Exposes the local 'item' variable to the parent component via the slot.
2
<template #default="{ item, status }">
Destructures the exposed object in the parent to access data directly in the template.