Javascript 在 vue 中发出带参数的事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53738919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:10:00  来源:igfitidea点击:

Emit event with parameters in vue

javascriptvue.jscomponents

提问by user3348410

i'm trying to emit function with parameters like that.

我正在尝试使用这样的参数发出函数。

template: `
    <div class="searchDropDown">
    <div class="dropdown is-active">
    <div class="dropdown-trigger">
      <button class="button" aria-haspopup="true" aria-controls="dropdown-menu">
        <span>{{selectedItem}}</span>
      </button>
    </div>
    <div class="dropdown-menu" id="dropdown-menu" role="menu">
      <div class="dropdown-content">
        <a class="dropdown-item" v-for="item in drop" @click="$emit('select-menu-item($event)')">
          {{item.name}}
        </a>
      </div>
    </div>
  </div>
    </div>
  `

here is the i'm trying to pass item to method like a parameter.

这是我试图将项目像参数一样传递给方法。

here is my component which i try to emit function:

这是我尝试发出功能的组件:

<search-component v-bind="searchProps" @select-menu-item="selectedITem($event)"></search-component>

and here is my method:

这是我的方法:

selectedITem(arg1) {
      console.log("cl")
      console.log(arg1)
    }

here is if i'm not trying to pass parameter everything well work so my method selectedITemis working. When i try to pass parameter like that nothing happened and i'm not getting some error.

这是如果我不试图传递参数一切正常,所以我的方法selectedITEm正在工作。当我尝试传递这样的参数时,什么也没发生,也没有出现错误。

回答by Abana Clara

The following argument(s) in $emit()are the arguments in your emitted function.

以下参数$emit()是您发出的函数中的参数。

$emit('select-menu-item', $event, 1, 2, 3, 4, "cupcakes")

and in your component method.

并在您的组件方法中。

selectMenuItem: function(evt, num1, num2, num3, num4, food){

}

And in your actual component markup, you don't need to add arguments, just write the reference to the method without parenthesis.

并且在您的实际组件标记中,您不需要添加参数,只需编写不带括号的对方法的引用。

<search-component v-bind="searchProps" @select-menu-item="selectMenuItem">


SAMPLE

样本

window.onload = function(){
 const component = function() {
    return {
       template: `
       <div>
         <button @click="$emit('click-me', 'foobar')">
            Click Me
         </button>
       </div>
       `,
       props: ["data"]
    }
 }

 new Vue({
       el: container,
       data: {},
       components: { "my-component": component(), },
       methods: {
          clickMe: function(str){
            console.log(str);
          }
       }
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="container">
  <my-component :data=$data @click-me="clickMe"></my-component>
</div>