vue.joedoe.dev

← All the recipesComponents

A generic component with typed slots

generic="T" and defineSlots: the list works for anything with an id, and inside the slot TypeScript knows what each item is.

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

↑↓ move · ↵ open · esc close