Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

People also ask

What is V-on in VUE JS?

The v-on:click directive is a Vue. js directive used to add a click event listener to an element. First, we will create a div element with id as app and let's apply the v-on:click directive to a element. Further, we can execute a function when click even occurs. Syntax: v-on:click="function"

What is two-way binding Vue?

Two-way binding is a powerful feature that, if used properly, can significantly speed up your development process. It reduces the complexity of keeping user input consistent with the application data model. In Vue, two-way binding is accomplished using the v-model directive.

What is event modifiers in VUE JS?

Vue provides event modifiers for v-on by calling directive postfixes denoted by a dot. .stop. .prevent. .capture.


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.


You can also do something like this...

<input @input="myHandler('foo', 'bar', ...arguments)">

Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.


Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:

<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>