JAVASCRIPT
Empowering Parent Components with Data from Child Scoped Slots in Vue 3
Discover how to render dynamic content in parent components using Vue 3's scoped slots, enabling children to expose data for flexible customization.
// MyList.vue (Child Component)
<template>
<div>
<h2>{{ title }}</h2>
<ul>
<li v-for="item in items" :key="item.id">
<slot name="item" :item="item" :index="item.id"> <!-- Scoped Slot -->
<!-- Fallback content -->
{{ item.name }}
</slot>
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
title: String,
items: Array
}
};
</script>
// App.vue (Parent Component)
<template>
<MyList :items="products" title="Our Products">
<template v-slot:item="slotProps"> <!-- Accessing slotProps from child -->
<div :style="{ color: slotProps.item.price > 50 ? 'red' : 'green' }">
<strong>{{ slotProps.item.name }}</strong> - ${{ slotProps.item.price }}
<span v-if="slotProps.item.price > 50"> (Premium)</span>
<small> (Index: {{ slotProps.index }})</small>
</div>
</template>
</MyList>
<hr/>
<MyList :items="services" title="Our Services">
<template v-slot:item="{ item, index }"> <!-- Destructuring slotProps -->
<p>Service: {{ item.name }} (ID: {{ index }})</p>
</template>
</MyList>
</template>
<script>
import MyList from './MyList.vue';
export default {
components: { MyList },
setup() {
const products = [
{ id: 1, name: 'Laptop', price: 1200 },
{ id: 2, name: 'Mouse', price: 25 },
{ id: 3, name: 'Keyboard', price: 75 }
];
const services = [
{ id: 10, name: 'Web Development', price: 5000 },
{ id: 11, name: 'SEO Optimization', price: 1500 }
];
return { products, services };
}
};
</script>
How it works: Scoped slots in Vue 3 allow child components to provide data back to the parent for rendering within the slot's content. In this example, `MyList` (the child) iterates over `items` and exposes each `item` and its `index` via its named slot `item`. The `App.vue` (parent) then uses `<template v-slot:item="slotProps">` or destructuring `v-slot:item="{ item, index }"` to access this data and render highly customized list items. This pattern provides immense flexibility, letting the child component manage the list structure while the parent controls the presentation of individual list elements based on the child's data.