Performance: Typing emits
Typing emits affects how Vue components communicate events, impacting runtime checks and bundle size.
import { defineComponent } from 'vue'; export default defineComponent({ emits: { update: (payload: number) => typeof payload === 'number' }, methods: { sendUpdate() { this.$emit('update', 123); } } });
export default { emits: ['update'], methods: { sendUpdate() { this.$emit('update', 123); } } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Untyped emits | No direct DOM ops | 0 | 0 | [!] OK |
| Typed emits with validation | No direct DOM ops | 0 | 0 | [OK] Good |
defineEmits in a Vue component?defineEmitsdefineEmits is used inside <script setup> to specify which events a component can send out.
It declares event names and their payload types to improve type safety and tooling support.
submit with a payload of type string in Vue 3 <script setup>?defineEmits with a TypeScript type object describing event names and their payload function signatures.defineEmits<{ submit: (payload: string) => void }>() which types the submit event with a string payload.<script setup> code:const emit = defineEmits<{ update: (value: number) => void }>();
emit('update', 42);update with a string payload like emit('update', 'hello')?update event expects a payload of type number as declared in defineEmits<{ update: (value: number) => void }>().'hello' violates the type signature, so TypeScript will report a compile-time error before running.<script setup> code snippet:const emit = defineEmits<{ save: (data: object) => void }>();
emit('save');save event expects a payload argument of type object.emit('save') is missing the required payload argument, causing a type error.string or number payload with the event name change. Which is the correct way to type this using defineEmits?|, e.g., string | number.change event with a payload that can be either string or number.& which means both types simultaneously (impossible). const emit = defineEmits<{ change: (value: any) => void }>() uses any which loses type safety.Pass the test and this pattern moves unknown