javascript / intermediate
Snippet
Flexible Composition with Scoped Slots
Scoped slots allow a child component to pass data back up to the parent through the slot mechanism. Using the 'let:' directive, the parent can access variables defined within the child, enabling highly reusable component patterns like data tables or lists.
snippet.js
1
2
3
4
5
6
7
<!-- Child.svelte --><slot {item} index={i}></slot><!-- Parent.svelte --><Child let:item let:index><p>{index}: {item.text}</p></Child>
svelte
Breakdown
1
<slot {item} index={i}></slot>
Exposes the 'item' and 'index' variables to the parent component.
2
let:item let:index
Receives the child's data and makes it available within the parent's template.