Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
JeanValjean Avatar asked Oct 19 '25 10:10

JeanValjean


1 Answers

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

like image 98
ittus Avatar answered Oct 20 '25 23:10

ittus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!