access value of object sent with eventbus in vue js

2.1k Views Asked by At

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

1

There are 1 best solutions below

1
On

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));