Child to Parent Communication in Vue

Last Updated: May 28, 2021

When you work with Vue components you will have to pass parameters from child components to parent.

We cab use events to pass data (vue emit to parent)

We have the following Vue component

Vue.component('child', {
      template:` <div>
           <input type="text" v-model="fname" />
           <button id="btn" @click="$emit('parentfunc',fname)" > Add Product </button>
        </div>
      `,

      data: function () {
        return {
          fname: ''
        }
      }
   
    }) 

 new Vue({
        el: "#root",
        methods :{
           mainfunc: function(value){
            alert("Text box value is " + value)
           }
         }
       })
Vue.component('child', {
      template:`
      `,

      data: function () {
        return {
          fname: ''
        }
      }
   
    }) 

You have text field with v-model='fname'
Button has the click event and I am going to pass the fname to the function parentfunc in parent element

This is the root element with the child component. In this component you are calling the mainfunc function in Vue instance

 
 

Your Vue instabce will be

new Vue({
        el: "#root",
        methods :{
           mainfunc: function(value){
            alert("Text box value is " + value)
           }
         }
       })

You have the mainfunc function to receive one argument. When user clikc on the button this method will be called and parameter will be displayed

If you put all pieces together you can have following code