Pass data from child to parent in Vuejs (is it so complicated?)
Asked Answered
P

3

93

I have read about it:

vuejs update 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 pass a data object from child to parent. I have used $emit to pass data to parent component but it doesn't works. Do you know what is wrong? You can check 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>
Puzzle answered 11/4, 2017 at 0:18 Comment(0)
A
71

You aren't listening to the event. I changed the event name to clicked-show-detail. Try this.

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>

Example.

Adjustment answered 11/4, 2017 at 0:40 Comment(2)
@Puzzle @clicked-show-detail is a short way of saying v-on:clicked-show-detail. It's how you define an event listener. In this case it says, call the clickedShowDetailModal method when the event fires. See vuejs.org/v2/guide/events.html#Listening-to-EventsAdjustment
Took longer than expected for me to realize that you don't include the () at the end of the function call in the parent. In other words @clicked-show-detail="clickedShowDetailModal" NOT @clicked-show-detail="clickedShowDetailModal()"Bryon
C
126

Props are for parent -> child

You can use $emit for child -> parent

v-on directive captures the child components events that is emitted by $emit

Child component triggers clicked event :

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

Parent component receive clicked event:

<div>
    <child @clicked="onClickChild"></child>
</div>

...

export default {
  methods: {
      onClickChild (value) {
          console.log(value) // someValue
      }
  }
}
Clef answered 24/9, 2018 at 12:44 Comment(1)
Having export default MyComponentName extends Vue the methods prop causes error Property 'methods' has no initializer and is not definitely assigned in the constructor. and it doesn't work.Population
A
71

You aren't listening to the event. I changed the event name to clicked-show-detail. Try this.

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>

Example.

Adjustment answered 11/4, 2017 at 0:40 Comment(2)
@Puzzle @clicked-show-detail is a short way of saying v-on:clicked-show-detail. It's how you define an event listener. In this case it says, call the clickedShowDetailModal method when the event fires. See vuejs.org/v2/guide/events.html#Listening-to-EventsAdjustment
Took longer than expected for me to realize that you don't include the () at the end of the function call in the parent. In other words @clicked-show-detail="clickedShowDetailModal" NOT @clicked-show-detail="clickedShowDetailModal()"Bryon
O
7

Nightmare to find "hello world" example out there for $emit so I added the example below (Minimal lines of code + semantic names of functions).

"Hello world" On click change parent data

Vue.component('child', {
  template: `
<div class="child">
<button v-on:click="childMethod">CLICK - child Method pass data from product component</button>
</div>
`,
  data: function () {
    return {
      child_msg: "message from child"
    }
  },
  methods: {
    childMethod: function() {
      this.$emit('child-method', this.child_msg)
    }
  }
})

var app = new Vue({
  el: '#app',
  data: {
    msg: "I am the blue parent!!!!!!!!!!!!!!!!!!",
  },
  methods: {
    updateParent(value_from_child) {
      this.msg = value_from_child;
      alert("hello child" + value_from_child)
    }
  }
})
.child{ background: gray; padding: 15px; }
button{ cursor: pointer; }
#app{ border: 1px red dashed; padding: 15px; background: lightblue; color: blue;
}
<div id="app">
  <p>{{msg}}</p>
  <!-- ###### The trick happens her ###### -->
  <child class="child" v-on:child-method="updateParent"></child>
</div> 

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

codepen: https://codepen.io/ezra_siton/pen/YzyXNox?editors=1010

Officiate answered 12/4, 2020 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.