vue.joedoe.dev

← Totes les receptesComponents

Un component genèric amb slots tipats

generic="T" i defineSlots: la llista serveix per a qualsevol cosa amb id, i dins l'slot TypeScript sap què és cada item.

Vue SFC
<script setup lang="ts" generic="T extends { id: string | number }">
/*
 * One list for anything with an id: the parent decides how each item looks
 * through the #item slot, and TypeScript knows what `item` is in there.
 */
const { items } = defineProps<{ items: T[] }>();
const selected = defineModel<T | undefined>();

defineSlots<{
	item(props: { item: T; active: boolean }): unknown;
}>();
</script>

<template>
	<ul class="pick">
		<li v-for="item in items" :key="item.id">
			<button :aria-pressed="selected?.id === item.id" @click="selected = item">
				<slot name="item" :item="item" :active="selected?.id === item.id" />
			</button>
		</li>
	</ul>
</template>

Elige un disco

↑↓ moure's · ↵ obrir · esc tancar