Scoped Slot in Vue 2 (Options API)
With scoped slots, the child component can pass data to the slot content in the parent. That way, the parent can decide how to render data coming from the child.
1. Child Component (List.vue)
<template>
<ul>
<!-- we expose each item to the slot -->
<li v-for="(item, index) in items" :key="index">
<!-- default slot gets props -->
<slot :item="item" :index="index">
<!-- fallback content if parent doesn't use scoped slot -->
{{ index }} - {{ item }}
</slot>
</li>
</ul>
</template>
<script>
export default {
name: "List",
props: {
items: {
type: Array,
required: true
}
}
}
</script>
2. Parent Component (App.vue)
<template>
<div>
<h1>Scoped Slots Example</h1>
<!-- Using scoped slot -->
<List :items="categories">
<template v-slot:default="slotProps">
<!-- slotProps.item and slotProps.index come from child -->
<strong>{{ slotProps.index + 1 }}.</strong> {{ slotProps.item.toUpperCase() }}
</template>
</List>
<!-- Without scoped slot (fallback from List.vue will be used) -->
<List :items="tags" />
</div>
</template>
<script>
import List from "./List.vue";
export default {
name: "App",
components: { List },
data() {
return {
categories: ["News", "Sports", "Entertainment"],
tags: ["vue", "laravel", "slots"]
};
}
}
</script>