Generic components let you create flexible parts that work with different data types. This saves time and keeps your code clean.
0
0
Generic components in Vue
Introduction
You want one component to show different types of lists, like users or products.
You need a reusable button that can handle different actions and styles.
You want to build a form input that works with various data types like text or numbers.
You want to avoid repeating similar components for similar tasks.
You want to pass different content to a component but keep the same structure.
Syntax
Vue
<script setup lang="ts"> import { defineProps } from 'vue' type Item = { id: number name: string } const props = defineProps<{ items: Item[] }>() </script> <template> <ul> <li v-for="item in props.items" :key="item.id">{{ item.name }}</li> </ul> </template>
Use defineProps with TypeScript to specify the data type your component accepts.
Generic components work well with v-for to loop over different data arrays.
Examples
This example shows a generic list component for users with
username.Vue
<script setup lang="ts"> interface User { id: number username: string } const props = defineProps<{ items: User[] }>() </script> <template> <ul> <li v-for="user in props.items" :key="user.id">{{ user.username }}</li> </ul> </template>
This example shows the same component used for products with
title.Vue
<script setup lang="ts"> interface Product { id: number title: string } const props = defineProps<{ items: Product[] }>() </script> <template> <ul> <li v-for="product in props.items" :key="product.id">{{ product.title }}</li> </ul> </template>
Sample Program
This generic component shows a list of items with accessible markup. Each item is keyboard focusable for better navigation.
Vue
<script setup lang="ts"> interface Item { id: number label: string } const props = defineProps<{ items: Item[] }>() </script> <template> <section aria-label="Generic item list"> <ul> <li v-for="item in props.items" :key="item.id" tabindex="0">{{ item.label }}</li> </ul> </section> </template>
OutputSuccess
Important Notes
Always add key in v-for for better rendering performance.
Use semantic HTML and ARIA labels for accessibility.
Generic components work best with TypeScript to catch errors early.
Summary
Generic components let you reuse one component for many data types.
Use TypeScript and defineProps to specify the data shape.
Keep accessibility and keyboard navigation in mind.