vue.jsvuejs2vue-componentvue-events

How could the Vue app pass the additional parameters to the event listener when using vm.$once()?


In the Vue app , it could add the event listener that is called one time by using vm.$once.
For example, in the child component of Vue App, it could emit the event using vm.$emit('myEvent', data). emit event

And then it could be processed by adding the event listener to this event using vm.$once in the Vue app.
At this time, I want to pass the additional data to event handler.

I've tried as following. But it throws an error.

Uncaught ReferenceError: $event is not defined

    //In the Vueapp
    this.$refs.child.$once(
      'myEvent', this.eventHandler($event, additional_data)
    );

But I think that it could pass the additional data when using v-on.

  <child-component ref="child" v-on:myEvent="eventHandler($event, additional_data)"></child-component>   
   //$event is the data emitted from the event , "myEvent".

When using vm.$once or vm.$on, couldn't it pass the additional parameter?

Note: the reason that I use vm.$once is that I want to execute the eventHandler only one time when emitting the custom event, myEvent and add it dynamically .


Solution

  • You need to capture the arguments passed into the event handler. You can do this by using an anonymous function for the handler that calls your method. For example

    this.$refs.child.$once('myEvent', $event => {
      this.eventHandler($event, additional_data)
    })
    

    You could also get fancy with Function.prototype.bind() however you would have to reverse the arguments list as bind prepends arguments.

    For example

    methods: {
      eventHandler(data, $event) { // reversed argument list
        // etc
      }
    }
    

    and

    this.$refs.child.$once('myEvent', this.eventHandler.bind(this, additional_data))