Discover how one smart component can replace dozens of copies and save you hours!
Why Generic components in Vue? - Purpose & Use Cases
Imagine building many similar UI parts, like buttons or cards, each slightly different but mostly the same.
You write separate code for each one, copying and changing bits manually.
Copying code for each variation leads to mistakes and makes updates a nightmare.
If you want to change a small detail, you must find and fix it everywhere.
This wastes time and causes bugs.
Generic components let you write one flexible piece of code that works for many cases.
You just tell it what to show or how to behave, and it adapts automatically.
const ButtonPrimary = {...}; const ButtonSecondary = {...}; // lots of repeated code<GenericButton type="primary" /> <GenericButton type="secondary" />
Write once, reuse everywhere with easy customization, saving time and avoiding errors.
A shopping site uses one generic product card component to show different products with different images and prices, instead of separate cards for each product.
Manual copying causes bugs and wastes time.
Generic components let one code serve many needs.
This makes apps easier to build and maintain.
Practice
generic components in Vue?Solution
Step 1: Understand generic components purpose
Generic components are designed to be reusable with different data types, so you don't rewrite similar components for each type.Step 2: Compare options to this purpose
Options B, C, and D describe unrelated features. Only They allow reusing one component for different data types. matches the core benefit of generic components.Final Answer:
They allow reusing one component for different data types. -> Option AQuick Check:
Generic components = reuse for many data types [OK]
- Confusing generic components with styling features
- Thinking generic components handle routing
- Assuming generic components improve load speed automatically
Solution
Step 1: Recall TypeScript generic prop syntax in Vue
UsingdefinePropswith a generic type requires specifying the prop shape with a type parameter, like{ item: T }.Step 2: Analyze each option
const props = defineProps<{ item: T }>(); correctly usesdefineProps<{ item: T }>(). const props = defineProps<T>(); misses the prop shape object. const props = defineProps(['item']); uses string array syntax, not generic. const props = defineProps({ item: String }); uses a fixed type, not generic.Final Answer:
const props = defineProps<{ item: T }>(); -> Option BQuick Check:
Generic props need object shape with type parameter [OK]
- Using array syntax instead of type object for generic props
- Omitting the prop shape object in defineProps
- Using fixed types instead of generics
item is a string "Hello"?const props = defineProps<{ item: T }>();
const item = props.item;
return <div>{typeof item}: {item}</div>;Solution
Step 1: Understand the typeof operator on the prop
Thetypeofoperator returns the type of the value at runtime. Sinceitemis "Hello", a string,typeof itemis "string".Step 2: Determine the rendered output
The returned JSX renders a div with text: "string: Hello".Final Answer:
<div>string: Hello</div> -> Option DQuick Check:
typeof 'Hello' = string, so output matches [OK]
- Confusing typeof result with the value itself
- Expecting object or number type for string value
- Assuming runtime error without type issues
const props = defineProps<{ item: T }>();
const item = props.item;
console.log(item.value);Solution
Step 1: Analyze usage of
Accessingitem.valuevalueis valid only ifitemis a Vue ref. The generic typeTcould be any type, soitemmight not havevalue.Step 2: Check other options
Missing import ofdefinePropscauses syntax error. is incorrect becausedefinePropsis globally available in Vue SFCs. Generic typeTmust be declared before use. is incorrect becauseTis assumed declared in the generic context. Props must be defined as an array, not an object. is wrong because props can be defined as an object type.Final Answer:
Accessingvalueassumesitemis a ref, but it may not be. -> Option AQuick Check:
Accessing .value requires ref type, generic may not be ref [OK]
- Assuming generic type is always a ref
- Thinking defineProps needs import in SFC
- Believing props must be array, not object
Solution
Step 1: Define generic props for list of items
UsingdefineProps<{ items: T[] }>()correctly types the prop as an array of generic typeT.Step 2: Use slots with
Passing each item as a slot prop allows flexible rendering by the parent component, which is the correct pattern for generic components with slots.v-forto render each itemStep 3: Evaluate other options
UsedefineProps(['items'])and render items directly without slots. lacks generics and slots. UsedefineProps<{ items: any[] }>()and hardcode item rendering inside component. usesanylosing type safety and hardcodes rendering. UsedefineProps<{ items: T }>()and render items without looping. usesTinstead ofT[]and misses looping.Final Answer:
UsedefineProps<{ items: T[] }>()and a default slot withv-forpassing each item as slot prop. -> Option CQuick Check:
Generic list + slot with v-for = UsedefineProps<{ items: T[] }>()and a default slot withv-forpassing each item as slot prop. [OK]
- Using single item type instead of array for list props
- Not using slots for flexible item rendering
- Hardcoding rendering inside generic component
Ready to prove it?
Pass the test and this pattern moves unknown
