本文介绍了内联(模板内)事件处理程序中的 Vue 2 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在内联/模板内处理程序中访问传递给发出的事件的参数/参数?类似的东西:

Is it possible to access arguments/parameters passed to an emitted event within an inline / in-template handler? Something like:

<component @some-event="someObject.field = $arguments[0]"></component

我真正想做的是为作用域中的对象赋值.我知道我可以创建一个方法来执行此操作并将其用作事件的处理程序,但我想知道这是否可以用作内联语句.

What I'm trying to do exactly is assign a value to an object in the scope. I know I can create a method to do that and use it as a handler for the event but I was wondering if this could work as an inline statement.

推荐答案

它不是$arguments[0],而是arguments[0](没有$).我很惊讶它实际上可以在内联处理程序中工作.所以下面的代码是有效的并且可以工作:

It is not $arguments[0], but just arguments[0] (without the $). I am surprised that it actually works in the inline handler. So the following code is valid and will work:

<component @some-event="someObject.field = arguments[0]"></component>

内联处理程序中的方法的文档指定$event 作为获取通过事件传递的第一个参数的特殊变量.我一直用到现在.

The docs for Methods in Inline Handlers specifies $event as a special variable that gets the first parameter passed via event. I have always used it till now.

阅读你的问题后,更多的研究让我找到了这个参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

After reading your question, a bit more research led me to this reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

似乎每个 javascript 函数都有一个名为 arguments 的局部变量,当函数需要获取可变数量的参数时使用该变量.

It seems every javascript function has a local variable called arguments, which is used when a function is expected to get variable number of arguments.

使用 arguments[] 作为内联语句绝对是可能的,但在 vue.js 框架的上下文中没有记录.另一方面,如果你在事件的内联处理程序中使用 $event,感觉更安全,因为它被清楚地记录并且不会在 Vue.js 的未来版本中中断

Using arguments[] as inline statements is definitely possible, but not documented anywhere in the context of vue.js framework. On the other hand, if you use $event in inline handler for events, it feels safer as it is documented clearly and will not break in a future version of Vue.js

$event 的示例用法:

<component @some-event="someObject.field = $event"></component>

这篇关于内联(模板内)事件处理程序中的 Vue 2 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:25