在 Vue 中将多个参数传递给自定义事件

发布于 2025-01-19 14:16:20 字数 699 浏览 0 评论 0 原文

根据&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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏了南城 2025-01-26 14:16:20

我最近在项目中做到了这一点。
在您的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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文