rubie
rubie

Reputation: 67

How do I use $emit in the loop to pass the array value to the parent?

The child component will pass the value to the parent component through a loop And the parent component will do something with the value

I have a mistake, the parent component cannot receive the child component, and each passed value will be missing

child component

 let array =[{a:'1',b:'2'},{a:'3',b:'4'},{a:'5',b:'6'},{a:'1',b:'2'},....]
 for(let index in array){
     this.$emit('update', array[index])
 }

parent component

 update(product) {
     console.log(product);
 }

In my console I can only get part of the children pass value

What is this error and how can I fix it?

This is my sample, although the error cannot be reproduced, the code is the same, except that the parent does not display all

example

Upvotes: 0

Views: 150

Answers (1)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27222

Your code should work fine, I did not see any issue in your code. I am assuming you are capturing the event emitted from the child into the parent component like this.

<child @update="update"></child>

Working Demo :

Vue.component('child', {
  data() {
    return {
      arr: [{a:'1',b:'2'}, {a:'3',b:'4'}, {a:'5',b:'6'},{a:'1',b:'2'}]
    }
  },
  mounted() {
    for(let index in this.arr){
      this.$emit('update', this.arr[index])
    }
  }
});

var app = new Vue({
  el: '#app',
  methods: {
    update(product) {
        console.log(product);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.0/vue.js"></script>
<div id="app">
  <child @update="update"></child>
</div>

Suggestion : To improve the performance, Instead of emitting each element into parent component, My suggestion would be to pass whole array and then do the data manipulations in the parent component itself.

Upvotes: 1

Related Questions