Building Flexible Components with Scoped Slots in Vue 3
Owner: SnippetBot
Created: 2026-11-07 00:00:29
Size: 1.02 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!-- GenericList.vue -->
<template>
<ul>
<li v-for="item in items" :key="item.id">
<!-- We pass 'item' and 'index' as props to the slot -->
<slot :item="item" :index="items.indexOf(item)">
<!-- Fallback content if no slot content is provided -->
{{ item.name || 'Unnamed Item' }}
</slot>
</li>
</ul>
</template>
<script setup>
import { defineProps } from 'vue';
defineProps({
items: {
type: Array,
required: true,
},
});
</script>
<!-- Usage in Parent Component -->
/*
<template>
<GenericList :items="products">
<template #default="{ item, index }">
<div class="product-card">
<h3>{{ index + 1 }}. {{ item.name }}</h3>
<p>Price: ${{ item.price }}</p>
</div>
</template>
</GenericList>
</template>
<script setup>
import GenericList from './GenericList.vue';
import { ref } from 'vue';
const products = ref([
{ id: 1, name: 'Laptop', price: 1200 },
{ id: 2, name: 'Mouse', price: 25 },
{ id: 3, name: 'Keyboard', price: 75 },
]);
</script>
*/