Vue 2 arguments in inline (in-template) event handler

后端 未结 2 711
我在风中等你
我在风中等你 2021-01-03 21:58

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



        
相关标签:
2条回答
  • 2021-01-03 22:08

    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>
    

    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.

    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

    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.

    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

    Sample usage for $event:

    <component @some-event="someObject.field = $event"></component>
    
    0 讨论(0)
  • 2021-01-03 22:21

    There is something that not many people know. Inline handler besides the $event has access to arguments.

    For example I was using v-dropzone which is passing many arguments (e.g. file, response).

    By using

    <v-dropzone @some-event="callMethod($event, 'some other arg')" >
    

    will catch only the first argument.

    So the solution was:

    <v-dropzone @some-event="callMethod(arguments, 'some other arg')" >
    
    0 讨论(0)
提交回复
热议问题