Junior
What does the $emit method do in Vue.js?
sobes.tech AI
Answer from AI
The $emit method is used to generate custom events from a child component. It is the primary way for a child component to interact with its parent in Vue's one-way data flow. It allows the child component to notify the parent that an event has occurred and, if necessary, pass data to it.
Working principle:
- In the child component,
$emit('eventName', payload)is called.eventNameis a string, the name of the event to be generated.payload(optional) is any data to pass to the parent component.
- In the parent component, when using the child component, this event is listened to using the
v-ondirective or the shorthand@. - When the event with the specified name is generated by the child component, the corresponding handler in the parent component is executed.
Example:
Child component (ChildComponent.vue):
<template>
<button @click="handleClick">Click me</button>
</template>
<script>
export default {
methods: {
handleClick() {
// Generate the 'buttonClicked' event without payload
this.$emit('buttonClicked');
}
}
}
</script>
Parent component (ParentComponent.vue):
<template>
<!-- Listen to the 'buttonClicked' event -->
<ChildComponent @buttonClicked="handleButtonClick" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleButtonClick() {
// This method will be executed when the child component generates 'buttonClicked'
console.log('Button in child component was clicked!');
}
}
}
</script>
$emit helps maintain the principle of one-way data flow, preventing direct modification of the parent's state by the child component. The child component only signals that something has happened, while the handling and state modification occur in the parent component.