1.

What do we use to pass data from child component to parent component and how (specify the steps required)?

Answer»

Values go up from child to parent using the $EMIT() event. 

Step 01: Invoke the $emit() method in the child to send a piece of the data to its parent component. 

//ChildComponent.vue  <template>   <button @click="$emit('name', 'RAJESH Bhagia')">click me</button>  </template> 

The first statement in the $emit method is the event name, and the second ARGUMENT is the actual data to be passed to the parent component. 

Step 02: Use the same event name prefixed with the @ symbol to define the child component inside the template in the parent component. 

Its VALUE will be a function, and it will have the actual value RETURNED in its argument. 

STEP 03: Declare the getName function inside the methods objects with an argument 

 

//ParentComponent.vue  <script>  import ChildComponent from './ChildComponent.vue'      export default {    components: {      ChildComponent    },    methods:{    getName(value) {//Step 03        console.log(value);     }  }  }  </script>    <template>  <h3>Below is the child component within the parent component!</h3>  <ChildComponent @name="getName"/> //STEP 02  </template> 

The value passed to the getName function is the one assigned on the ChildComponent which is “Rajesh Bhagia”.So it is the one which is passed to the parent component by emitting an event. 

>> Output after button click in child component 

>> Rajesh Bhagia


Discussion

No Comment Found

Related InterviewSolutions