Component Communication in Vue.Js
In modern front-end frameworks, the entire page is divided into small pieces of components. Each component has its own functionality & UI. Component-based architecture makes it easy to develop & maintain an application. During development, you may come across a situation where you need to share data between with other components. In this post, we are going to learn about many possible ways of achieving communication between components.
Vue.js allows component communication in the following ways:-
1. Parent to child communication (Using Props).
2. Child to parent communication (Using Events).
3. Communication between any component (Using Event Bus).
1. Parent to child communication:
In this type of communication, a parent passes the data to child by adding an argument in the component declaration.
Consider the above code. Here we have added an argument “message” in the child component declaration. For dynamically setting the value we have to add “ : ” before the argument.
In our child component, we have added an input argument “message” along with the data type “String”.
Props provide only one-way communication from a parent to child but vice-versa is not possible. Any changes in the values of an attribute/argument in the prop is directly reflected in the child.
But what if you want to call a method inside child component when the value is changed.
In the above example, we have added a property “watch” inside which a function to invoke the callMe() method is declared. This will ensure that when the value is changed callMe() function will be invoked.
2. Child to parent communication
In this type of communication, Events ensures communication from child to parent.
Here in the “ChildComponent” we are firing an event that emits a message and its parent can get this message using the “v-on:” directive.
In events, arguments are optional. You can pass ’n’ number of arguments. When child component will fire the event “messageFromChild()”, “childMessageReceived()” function will be called.
3. Communication between any components using Event Bus
Event Bus is not limited to a parent-child relation. You can share information between any components.
In the above AbcComponent, we are firing an event “message_from_abc” and passing arguments. Arguments are optional here. Any other component can listen to this event.
In XyzComponent to listen an event, we have to register it first. We can do so by putting an event listener inside mounted() callback. This callback will be triggered when an event is fired from any component.
Alternatively, we can use Vuex a redux based state management tool for Vue.
We’ll discuss Vuex on my next article. Stay tuned….