根据&lt; childComponent @click =“ $ emit('myevent',1)” /&gt; < /code>和,如果父母在父级上的事件处理程序是一个方法,此值将作为其参数传递。但是,如果我想将另一个参数传递给处理程序时,该论点在父部件中调用它时该怎么办?我可以简单地编写&lt; parentComponent @myEvent =“ eventHandler(2)” /&gt; < /code>,然后让函数接受两个参数,例如这样?
function eventHandler(childArgument, parentArgument) {
// I want to have access to the value 1 from the child and the value 2 from the parent component here.
// If I do it like this, will childArgument contain the 1 and parentArgument the 2?
}
如果这不起作用,我该怎么做?
According to the Vue documentation - I linked to the relevant page - I can emit a custom event together with a value by typing <ChildComponent @click="$emit('myEvent', 1)" />
and, if the event handler on the parent component is a method, this value will be passed as its argument. But what if I want to pass another argument to the handler when calling it in the parent component? Can I simply write <ParentComponent @myEvent="eventHandler(2)" />
and then have the function accept two arguments, like this?
function eventHandler(childArgument, parentArgument) {
// I want to have access to the value 1 from the child and the value 2 from the parent component here.
// If I do it like this, will childArgument contain the 1 and parentArgument the 2?
}
And if this doesn't work, how would I have to do this?
发布评论
评论(1)
我最近在项目中做到了这一点。
在您的ChildComponent和parentComponent的
中
示例 2,...参数)“/&gt;
然后您的eventhandler看起来像
function eventhandler(parentArgument,childargument){...}
您可能可以根据需要更改订购但这对我有用。同样,我相信建议将烤肉串盒用于HTML元素。
I just recently did this in my project.
In your example of a ChildComponent and ParentComponent you can have
<ChildComponent @click="$emit('myEvent', 1)" />
<ParentComponent @myEvent="eventHandler(2, ...arguments)" />
Then your eventHandler would look like this
function eventHandler(parentArgument, childArgument) { ... }
You can probably change the ordering as you wish but this worked for me. Also just a side note I believe it's recommended to use kebab-case for the html elements.