An Overview of Component Communication in Vue.js

An Overview of Component Communication in Vue.js

In this article, we will learn about communication between components in Vue.js.

In this article, I would like to talk about the front-end framework, Vue js. It is not very difficult for those who are familiar with the concepts of Angular. In this article, we will learn about communication between components in Vue.js.

There are multiple ways for inter-component communication in Vue.js, as mentioned below.

  1. Using props
  2. Using event
  3. Using event bus to communicate between any component

The first way of communication from a child component to a parent component is using props.

Firstly, I am going to cast a light on props - What, why, and how to use props. Let's start with why we need props.

  • Props is known as one-way communication. It means Props allows you to pass the data from the parent component to the child component.
  • At any time, if the value will change in the parent component, then the new value is set to the child and rendered (behind the scenes, the hot modules replacement will work for rendering without a refresh ).

Let me give an example of props.

Go and create a component called parent component (Parent.vue).

<template>  
   <div>  
      <Child titleOfChild="Children Component"></Child>  
   </div>  
</template>  
<script>  
   // Path of child component  
   import { Child } from "./child.vue";  
   export default {  
      name: 'Parent',  
      components: {  
         Child  
         }  
   }  
</script>  

NOTE We have the child component tag () and here, we are passing data to child component as "titleOfChild".

Go and create a component called child component (Child.vue).

<template>  
   <div>  
      <h1>{{titleOfChild}}</h1>  
   </div>  
</template>  
<script>  
export default {  
   name: 'Child',  
   props: [  
   // camelCase in JavaScript  
   'titleOfChild'  
   ]  
}  
</script>  

NOTE In child component, we are using props to get the value ("titleOfChild") which is passing from the parent component and we can directly use this value in the template using an expression (double curly braces).

Props can be used in different ways like,

  1. Passing static or dynamic props
  2. Passing a Number
  3. Passing a Boolean
  4. Passing an Object
  5. Passing an Array

The second way of communication in Vue.js from parent component to child component is described below.

Now, I am going to show how we can pass data from a child component to the parent component.

For this, we need to emit an event.

For example,

STEP 1

Go and create a child component (Child.vue).

<template>  
   <div class="submit-btn">  
      <p>  
         <input type="submit" value="Submit" @click="callingParentComponentMethod">  
         "OR"  
         <input type="submit" value="Submit" v-on:click="callingParentComponentMethod">  
      </p>  
   </div>  
</template>  
<script>  
export default {  
   name: "Child",  
   methods: {  
      // This method will call on click of submit button  
      callingParentComponentMethod() {  
      // emit the event and call the parent component  
      this.$emit("setParentComponentDetails");  
      }  
   }  
// props: ["cTitle", "cAbout", "cHome"]  
};  
</script> 

NOTE In the template section, we are calling a method "callingParentComponentMethod" on the click of Submit.

You can call the method in two ways like @click or v-on:click .

Inside the script section, we are using the "this.$emit()" method to call the parent component.

You can pass some parameters from child component to parent component. Below are the examples.

this.$emit("setParentComponentDetails", param1, param2);  

STEP 2

Go and create a parent component (Parent.vue).

<template>  
   <div>  
      <Child @setParentComponentDetails="setDetailsForComponent" > </Child>  
   </div>  
</template>  
<script>  
// Path of child component  
import { Child } from "./child.vue";  
   export default {  
   name: 'Parent',  
   components: {  
      Child  
   },  
   methods: {  
      // Called by child component  
      setDetailsForComponent() {  
      console.log("Calling from child component");  
      }  
   }  
}  
</script>  

NOTE In template section, we are setting an event ("setParentComponentDetails") which is sent by the child component and called method ("setDetailsForComponent()") inside the script section.

Scenario

If you are getting some parameters from child component, then you can receive these parameters in parent component inside the method section like:

setDetailsForComponent(param1, param2){  
   Console.log(param1 + '' + param2);  
}  

The third way of communication in Vue.js when there is no relationship between components is given below.

Firstly, we need to understand what is the meaning of no relationship between components. It means when two sibling components (no parent-child relationship) are communicating, we can use the EVENT BUS/ publish-subscribe pattern.

We can use Event Bus on the simplest architecture. It allows us to emit an event in one component and listen for that event in another component.

Below are the several steps to get this communication working.

Step 1 - Initialization of Event Bus

Create a file 'event-bus.js' and write the below code.

import Vue from 'vue';  
export const EventBus = new Vue();  

Step 2 - Using the Event bus

We have created the event bus; now, we need to import that in our component.

import { EventBus } from "./event-bus.js";  

Step 3 - Sending Event from component

We need to emit an event whenever someone clicks the button.

Create a new component 'component1.vue' and write the below code.

<template>  
   <div class="click-me">  
      <button @click="emitGlobalClickEvent">Please Click me</button>  
   </div>  
</template>  
<script>  
// Import the EventBus we just created.  
import { EventBus } from "./event-bus.js";  
   export default {  
   name:'component1',  
   data() {  
   return {  
      Count: 0  
   };  
},  
methods: {  
emitGlobalClickEvent() {  
   this.Count++;  
      // Send the event on a channel (i-got-clicked) with a payload (the click count.)  
      EventBus.$emit("clicked-event", this.Count);  
      }  
   }  
};  
</script>  

NOTE Here, we are setting Event "clicked-event" which will be use as a receiving event in other components.

Step 4 - Receiving/Listening Event

We need to listen to an event using Event.$on.

Create a new component, 'component2.vue,' and write the below code.

<script>  
// Import the EventBus.  
import { EventBus } from "./event-bus.js";  
export default {  
   name: 'Component2',  
   mounted() {  
   // Listen for the 'clicked-event' and its payload.  
      EventBus.$on("clicked-event", Count=> {  
      console.log(`Oh, that's great. It's gotten ${Count} clicks! :)`);  
      });  
   }  
};  
</script>  

NOTE Here, we are listening to the event "clicked-event" inside the lifecycle hook 'mounted'.

ALTERNATIVE OPTION

Sometimes, you will get some complex scenarios. Then time, we have an option to use Vueex or any third-party libraries.

I hope this article will be useful and helpful to everyone. Thanks for reading :)

Happy coding!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.