JeanValjean
JeanValjean

Reputation: 17713

How to pass data with custom events using an event bus in Vue.js 2

I'm using Vue.js 2.5.x.

In my toy project, I've implemented an event bus (similarly to what shown here). The event bus is globally registered in Vue prototype as $eventBus.

Then I created a component that emits an event as follows

this.$eventBus.$emit('actionCompleted')

and another that registers to that event to execute its own function (myMethod), as shown below

export default {
  created: function () {
      this.$eventBus.$on('actionCompleted', this.myMethod)
  },
  methods: {
    myMethod () {
        console.log('myMethod called')
    }
  }
}

So far so good, all works as expected.

The question is: how can I pass an object to my custom event so that I can ship additional information to the listeners?

Upvotes: 4

Views: 7524

Answers (3)

Orlandster
Orlandster

Reputation: 4858

You can simply emit an object through your event bus:

this.$eventBus.$emit('actionCompleted', this.yourObject)

And then catch it like this:

export default {
  created: function () {
      this.$eventBus.$on('actionCompleted', this.myMethod)
  },
  methods: {
    myMethod (objectParams) {
        console.log('myMethod called', objectParams)
    }
  }
}

Upvotes: 3

Harsh Patel
Harsh Patel

Reputation: 6830

You can create event like this way for single argument:

this.$eventBus.$emit('actionCompleted',args)

You can pass multiples arguments by comma separate values.

multiples arguments:

this.$eventBus.$emit('actionCompleted',args1, args2 ...)

after passing that argument you can get as follow [for single argument]:

export default {
  created: function () {
      this.$eventBus.$on('actionCompleted', this.myMethod)
  },
  methods: {
    myMethod (args) {
        console.log('myMethod called', args)
    }
  }
}

Upvotes: 3

ittus
ittus

Reputation: 22393

You can pass your parameter as second argument

this.$eventBus.$emit('actionCompleted', objectParams)

export default {
  created: function () {
      this.$eventBus.$on('actionCompleted', this.myMethod)
  },
  methods: {
    myMethod (objectParams) {
        console.log('myMethod called', objectParams)
    }
  }
}

You can check following tutorial

Upvotes: 5

Related Questions