--- title: Always Declare Emits for Documentation and Validation impact: MEDIUM impactDescription: Undeclared emits cause warnings, break TypeScript inference, and prevent event validation type: best-practice tags: [vue3, emits, defineEmits, component-events, typescript, documentation] --- # Always Declare Emits for Documentation and Validation **Impact: MEDIUM** - Declaring emitted events with `defineEmits()` or the `emits` option is technically optional, but strongly recommended. Without declarations, Vue shows runtime warnings, TypeScript can't infer event types, and you lose the ability to validate event payloads. Declared emits also serve as self-documentation, making it immediately clear what events a component can emit. ## Task Checklist - [ ] Use `defineEmits()` in ` ``` Vue warns: ``` [Vue warn]: Component emitted event "select" but it is neither declared in the emits option nor as an "onSelect" prop. ``` ## Basic Declaration **Correct - Array syntax:** ```vue ``` **Correct - Options API:** ```js export default { emits: ['submit', 'cancel', 'update'], methods: { handleSubmit() { this.$emit('submit', this.formData) } } } ``` ## TypeScript Typed Emits **Correct - Type-based declaration (recommended for TypeScript):** ```vue ``` **Alternative syntax (Vue 3.3+):** ```vue ``` ## Event Validation You can validate event payloads at runtime: **Correct - Validation functions:** ```vue ``` Returning `false` from a validator logs a console warning but doesn't prevent the event from being emitted. ## Benefits of Declaring Emits ### 1. Fallthrough Attribute Separation Without declaration, native event listeners fall through to the root element: ```vue ``` ```vue ``` With declaration, Vue knows it's a component event: ```vue ``` ### 2. Self-Documentation ```vue ``` ### 3. IDE Support With declarations, your IDE can: - Autocomplete event names when using the component - Show event payload types - Warn about typos in event names - Navigate to event definitions ## $emit in Template vs emit in Script ```vue ``` ## Reference - [Vue.js Component Events - Declaring Emitted Events](https://vuejs.org/guide/components/events.html#declaring-emitted-events) - [Vue.js Component Events - Events Validation](https://vuejs.org/guide/components/events.html#events-validation) - [Vue 3 Migration - emits Option](https://v3-migration.vuejs.org/breaking-changes/emits-option)