在 Vue.js 中将事件和参数传递给 v-on [英] Passing event and argument to v-on in Vue.js
问题描述
我在 v-on:input
指令中传递了一个参数.如果我不通过它,我可以在方法中访问该事件.有什么方法可以在将参数传递给函数时仍然访问事件.并不是说我在使用 vue-router:
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:
这是不传参数的.我可以访问事件对象
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)
}
}
这是传递参数的时候.我无法访问事件对象
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/
推荐答案
如果要访问事件对象以及传递的数据,则必须通过 event
和 ticket.id
都作为参数,如下所示:
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)
}
}
参见工作小提琴:https://jsfiddle.net/nee5nszL/
如果您使用的是 vue-router,则可能必须使用 $event 在您的 v-on:input
方法中,如下所示:
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">
这里正在运行 fiddle.
这篇关于在 Vue.js 中将事件和参数传递给 v-on的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!