1

i used evntbus to pass data between two components in the first one when i click on the button the function submitted is executed like this and i send array of object to the other component

submitted(){
  this.products.push(this.product); 
  EventBus.$emit('prod', this.products); 
}

and in the other component:

created(){
  EventBus.$on('prod', function (productObject) {
    console.log('event received!', userObject);
    this.produc = productObject.products
    console.log('The product: ', this.produc)
  }.bind(this));
  console.log('User outside eventbus:', this.produc);
}

the problem is that i can't access to objects passed with eventbus in second component can't any one help me ? the value of productobject is

image

4
  • can you log productObject to the console? are you sure it contains a products property or is it an array? Commented Sep 5, 2017 at 14:12
  • i.sstatic.net/22hl7.png Commented Sep 5, 2017 at 14:23
  • Judging from the log you attached, productObject is an array with one element - as you emit this.products, not this.product. Commented Sep 5, 2017 at 15:56
  • can you explain more please ? i send products from the first component and then in second one i have an element in my data called produc and i affect to it value recieved from the firsyt one but when i log the console.log('The product: ', this.produc) it is shown undefined Commented Sep 5, 2017 at 16:02

1 Answer 1

2

First, it should be EventBus.$emit('prod', this.products);, as you emit the event on the EventBus, not on the component.

Second, you pass this.products (an array) into Event Bus, but seem to treat it as a single object in the handler function. Besides, you're trying to access some arbitrary value of it (products), apparently thinking that event data object somehow remembers in which variable it was stored. But it's not.

So, based on whether or not you actually need to pass the whole array of products into EventBus, you have two options:

1) if you do need this.products elsewhere, access its last element in that other component:

EventBus.$on('prod', function(products) {
  this.product = products[products.length - 1]; 
  console.log('The product: ', this.product);
}.bind(this));

2) if not, just send the single product and use it directly:

EventBus.$emit('prod', this.product);

// ...and in another component
EventBus.$on('prod', function(product) {
  this.product = product; 
  console.log('The product: ', this.product);
}.bind(this));
Sign up to request clarification or add additional context in comments.

1 Comment

thnx for your response i make a mistake when i copy the code i write it like you said but i can't access value in second component

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.