Passing event and argument to v-on in Vue.js

geckob picture geckob · Dec 4, 2016 · Viewed 141k times · Source

I pass a parameter in v-on:input directives. If I don't pass it, I can access the event in the method. Is there any way I can still access the event when passing the parameter to the function. Not that I am using vue-router:

This is without passing the parameter. I can access the event object

HTML

<input type="number" v-on:input="addToCart" min="0" placeholder="0">

Javascript

  methods: {
    addToCart: function (event) {

      // I need to access the element by using event.target
      console.log('In addToCart')
      console.log(event.target)
    }
  }

This is when passing the parameter. I can't access the event object

HTML

<input type="number" v-on:input="addToCart(ticket.id)" min="0" placeholder="0">

Javascript

  methods: {
    addToCart: function (id) {

      // How can I access the element by using event
      console.log('In addToCart')
      console.log(id)
    }
  }

Here is some snippet of the code, should be good enough to replicate the problem that I am having

https://jsfiddle.net/lookman/vdhwkrmq/

Answer

Saurabh picture Saurabh · Dec 4, 2016

If you want to access event object as well as data passed, you have to pass event and ticket.id both as parameters, like following:

HTML

<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">

Javascript

methods: {
  addToCart: function (event, id) {
    // use event here as well as id
    console.log('In addToCart')
    console.log(id)
  }
}

See working fiddle: https://jsfiddle.net/nee5nszL/

Edited: case with vue-router

In case you are using vue-router, you may have to use $event in your v-on:input method like following:

<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">

Here is working fiddle.