JAVASCRIPT
Mastering Scoped Slots for Flexible Component Rendering in Vue 3
Discover how to use Vue 3's scoped slots to pass data from a child component back to its parent, enabling highly customizable and reusable UI components.
// MyList.vue (Child Component)
<template>
<ul>
<slot v-for="item in items" :item="item" :key="item.id"></slot>
</ul>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([
{ id: 1, name: 'Apple', price: 1.00 },
{ id: 2, name: 'Banana', price: 0.50 },
{ id: 3, name: 'Cherry', price: 2.20 }
]);
</script>
// ParentComponent.vue
<template>
<MyList>
<template v-slot="{ item }">
<li>{{ item.name }} - ${{ item.price.toFixed(2) }}</li>
</template>
</MyList>
<h3>Alternative display:</h3>
<MyList>
<template #default="{ item }">
<li :style="{ color: item.price > 1.00 ? 'red' : 'green' }">
{{ item.name.toUpperCase() }} ({{ item.price }})
</li>
</template>
</MyList>
</template>
<script setup>
import MyList from './MyList.vue';
</script>
How it works: Scoped slots provide a powerful way for a child component to pass data back to its parent, allowing the parent to define how that data should be rendered. This makes components incredibly flexible and reusable, as the child controls the iteration (e.g., `v-for`) but the parent dictates the visual representation of each item using the data exposed via the slot props.