Vue.js Part 09 – Emit And Props
In this article, we will explore how to use $emit and props to facilitate component communication in Vue.js.
$emit
In Vue.js, the $emit method allows a child component to trigger custom events that can be listened to by its parent component. This is useful for passing data from a child component to its parent.
Here’s an example of how to use $emit in a child component:
// ChildComponent.vue
<template>
<button @click="emitData">Click me</button>
</template>
<script>
export default {
methods: {
emitData() {
this.$emit('custom-event', 'Hello from child component');
}
}
}
</script>
In the above example, when the button is clicked, the emitData method is called and it triggers a custom event named ‘custom-event’ and passes the string ‘Hello from child component’ as the data.
Props
Props are used to pass data from a parent component to a child component. This allows the parent component to communicate with its child component by passing data down as props.
Here’s an example of how to use props in a child component:
// ChildComponent.vue
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: ['message']
}
</script>
In the above example, the parent component can pass the message data down to the child component using a prop. The child component can then access and display the message using the {{ message }} syntax in the template section.
Component Communication Using $emit And Props
Now that we understand how $emit and props work, we can use them together to facilitate communication between components in Vue.js.
Here’s an example of how to use $emit and props together for component communication:
// ParentComponent.vue
<template>
<div>
<ChildComponent @custom-event="handleCustomEvent" :message="parentMessage" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from parent component'
}
},
methods: {
handleCustomEvent(data) {
console.log(data); // Output: Hello from child component
}
}
}
</script>
In the above example, the ParentComponent is listening for the ‘custom-event’ emitted by the ChildComponent. When the event is triggered, the handleCustomEvent method is called, and we can access the data passed from the child component. In this case, it will log ‘Hello from child component’ to the console. Additionally, the ParentComponent is passing the parentMessage down to the ChildComponent as a prop, which the ChildComponent can access and display in its template.
By using $emit and props, we can create a powerful system for communication between components in Vue.js, allowing for a seamless flow of data and events between different parts of our application.
Thanks❤
Great explanation…Keep up the good work!!!💛
Keep up the good work 🎉