Pass data from child to parent in Vuejs (how complicated?)

Thanks for reading my question.

I read about it

vuejs updates parent data from child component

https://forum.vuejs.org/t/passing-data-back-to-parent/1201/2

The concept is the same, I need to transfer the data object from child to parent, I used $ emit to transfer data to the parent component, but it does not work. Do you know what is wrong? Check out my code here:

Vue.component('list-products', { delimiters: ['[[', ']]'], template: '#list-products-template', props: ['products'], data: function () { return { productSelected: {} } }, methods: { showDetailModal: function (product) { console.log('click product in child, how can i pass this product to productSelected data in parent?'); console.log(product); this.productSelected = product; this.$emit('clickedShowDetailModal', product); } } }); var app = new Vue({ delimiters: ['[[', ']]'], el: '#resultComponent', data: { listProducts: [ {'name':'test1',id:1}, {'name':'test2',id:2}, {'name':'test3',id:3} ], productSelected: {} }, methods: { clickedShowDetailModal: function (value) { console.log('value'); console.log(value); this.productSelected = value; } } }); 
 <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="resultComponent" data-toggler=".small-up-2" class="row small-up-1"> <list-products :products="listProducts"></list-products> </div> <script type="text/x-template" id="list-products-template"> <div> <div class="column column-block" v-for="(product, index) in products" :product="product" :index="index" :key="product.id"> <li class="more-benefits"> <a @click="showDetailModal(product)">Click me [[ product.name ]] and check console.log ยป</a> </li> </div> </div> </script> 

Thanks in advance.

+19
source share
3 answers

You are not listening to the event. I changed the name of the event to clicked-show-detail . Try it.

In the showDetailModal method of your component.

 this.$emit('clicked-show-detail', product); 

In your Vue.

 <list-products :products="listProducts" @clicked-show-detail="clickedShowDetailModal"></list-products> 

An example .

+20
source share

Props for parent โ†’ child

You can use $emit for child โ†’ parent

V-on directive captures events of child components emitted by $ emit

The child component fires the clicked event:

 export default { methods: { onClickButton (event) { this.$emit('clicked', 'someValue') } } } 

Parent component receives clicked event:

 <div> <child @clicked="onClickChild"></child> </div> ... export default { methods: { onClickChild (value) { console.log(value) // someValue } } } 
+15
source share

@bereket gebredingle

Your onClickChild method in the parent does not listen for the event in the parameter.

 <div><child @clicked="onClickChild(&event)"></child></div> 
-2
source share

All Articles