Performance: Events for child to parent communication
This concept affects interaction responsiveness and rendering updates when child components notify parents.
<ChildComponent @customEvent="handleEvent" /> // Inside ChildComponent this.$emit('customEvent', data) // Parent method updates only necessary reactive state
<ChildComponent @customEvent="parentMethod" /> // Inside ChildComponent this.$emit('customEvent', data) // Parent method triggers heavy state changes or multiple DOM updates unnecessarily
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Parent updates many reactive states on child event | High (many nodes affected) | Multiple reflows | High paint cost | [X] Bad |
| Parent updates minimal reactive state on child event | Low (few nodes affected) | Single reflow | Low paint cost | [OK] Good |
$emit to send a custom event to the parent, which listens for it.update?@eventName or v-on:eventName to listen to events. The handler should be a method reference without parentheses.<Child @update='handleUpdate' /> uses @update='handleUpdate' correctly without calling the method immediately.export default {
emits: ['send'],
methods: {
notify() {
this.$emit('send', 'hello')
}
}
}<Child @send='receiveMessage' />
notify() is called in the child?export default {
methods: {
sendData() {
this.emit('update', 123)
}
}
}$emit, not emit.emits is recommended, not declaring does not cause this error.save and cancel, each with a payload. How should you define and emit these events properly in Vue 3 Composition API <script setup>?defineEmits returns an emit function. It can accept an object to define event names and validators or an array of event names.const emit = defineEmits({ save: null, cancel: null })
function onSave() { emit('save', data) }
function onCancel() { emit('cancel', reason) } uses defineEmits({ save: null, cancel: null }) which is valid and recommended for typing events. Then emits events with emit('save', data) and emit('cancel', reason).defineEmits(['save', 'cancel'])
function onSave() { emit('save', data) }
function onCancel() { emit('cancel', reason) } calls defineEmits without assigning the result to emit, so emit is undefined. defineEmits(['save', 'cancel'])
const emit = defineEmits(['save', 'cancel'])
function onSave() { emit('save', data) }
function onCancel() { emit('cancel', reason) } calls defineEmits twice which is invalid. const emit = defineEmits(['save', 'cancel'])
function onSave() { this.$emit('save', data) }
function onCancel() { this.$emit('cancel', reason) } uses this.$emit which is not available in <script setup>.Pass the test and this pattern moves unknown