javascript / intermediate
Snippet
Decoupling Logic with Scoped Slots
Scoped slots allow a child component to pass data back up to the parent's slot content. This pattern is essential for creating highly flexible UI components where the parent controls the rendering while the child controls the data flow.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- ListComponent.vue --><template><ul><li v-for="item in items" :key="item.id"><slot name="item" :data="item" :isLast="item.id === items.length">{{ item.defaultText }}</slot></li></ul></template><!-- Usage in Parent --><ListComponent :items="myList"><template #item="{ data, isLast }"><span :class="{ 'bold': isLast }">{{ data.label }}</span></template></ListComponent>
vue
Breakdown
1
<slot name="item" :data="item" ...>
The child 'exposes' data to the slot using attributes.
2
<template #item="{ data, isLast }">
The parent 'destructures' the exposed data for custom rendering.