How to access child method from the parent in Vue.js?


Let’s say you have two nested components i.e. a component inside another component. How will you be able to access the child methods from the parent? To access the child method from the parent method you could use ref. Or you can also access the descendants of a parent via the method this.$root (a parent component) which can access the child components using the this.$children array. In the same way, the child can access its parent via the this.$parent.

The vue.js basically warns against these for the below two reasons −

  • It tightly couples the parent to the child and vice versa.

  • The parent state can be modified by a child and is therefore unreliable.

So, we can also use the event interface implemented by Vue.js that allows communicating up and down the component tree.

  • $on() − This allows you to declare a listener on the Vue instance you want to listen to events.

  • $emit() − This allows you to trigger events on the same instance.

Example

Copy and paste the below code snipped in your Vue project and run the Vue project. You shall see the below output on the browser window.

  • FileName - app.js

  • Directory Structure -- $project/public -- app.js

// Defining the parent and child events
const events = new Vue({}),
parentComponent = new Vue({
   el: '#parent',
   ready() {
      events.$on('eventGreet', () => {
         this.parentMsg = `Heard the greeting event from Child component ${++this.counter} times..`;
      });
   },
   data: {
      parentMsg: 'Listening for an event..',
      counter: 0
   }
}),
childComponent = new Vue({
   el: '#child',
   methods: {
      greet: function () {
         events.$emit('eventGreet');
         this.childMsg = `Firing the greeting event ${++this.counter} times..`;
      }
   },
   data: {
      childMsg: 'Ready to fire an event.',
      counter: 0
   }
});
  • FileName - index.html

  • Directory Structure -- $project/public -- index.html

<!DOCTYPE javascript>
<javascript>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
   <body>
      <div id="parent">
         <h2>Parent Component</h2>
         <p>{{parentMsg}}</p>
      </div>
      <div id="child">
         <h2>Child Component</h2>
         <p>{{childMsg}}</p>
         <button v-on:click="greet">Greet</button>
      </div>
      <script src='app.js'></script>
   </body>
</javascript>

Run the following command to get the below output −

C://my-project/ > npm run serve	

Complete Example with javascript

Now let’s combine the two files- app.js and index.js to create a new javascript file

<!DOCTYPE javascript>
<javascript>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
   <body>
      <div id="parent">
         <h2>Parent Component</h2>
         <p>{{parentMsg}}</p>
      </div>
      <div id="child">
         <h2>Child Component</h2>
         <p>{{childMsg}}</p>
         <button v-on:click="greet">Greet</button>
      </div>
      <script>
         
         // Defining the parent and child events
         const events = new Vue({}),
         parentComponent = new Vue({
            el: '#parent',
            ready() {
               events.$on('eventGreet', () => {
                  this.parentMsg = `Heard the greeting event from Child component ${++this.counter} times..`;
               });
            },
            data: {
               parentMsg: 'Listening for an event..',
               counter: 0
            }
         }),
         childComponent = new Vue({
            el: '#child',
            methods: {
               greet: function () {
                  events.$emit('eventGreet');
                  this.childMsg = `Firing the greeting event ${++this.counter} times..`;
               }
            },
            data: {
               childMsg: 'Ready to fire an event.',
               counter: 0
            }
         });
      </script>
   </body>
</javascript>

When you run the above program, the default greeting events triggered. On clicking the Greet button, in the child component, it will show- Firing the greeting event 1 times.

In this tutorial, we discussed how to access the child method from the parent in Vue.js.

Updated on: 12-Apr-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements