使用 vue 中的参数发出事件

我正在尝试发出带有这样参数的函数。

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>
`

下面是 i 试图将 item 传递给像参数一样的方法。

下面是我尝试发出函数的组件:

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

这是我的方法:

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

这里是如果我不尝试传递参数一切工作,所以我的方法 选定项目是工作的。当我像这样传递参数时,什么也没有发生,我不会得到一些错误。

118540 次浏览

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

$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>

just adding more answer from @Albana Clara.

You can merge your parameter along with the event passed.

EXAMPLE:

<search-component v-bind="searchProps" @select-menu-item="selectMenuItem('test', ...arguments)">
selectMenuItem: function(a, b) {
console.log(a + " " + b);
// test foobar
}

If anyone searching how emits work in Vue3 with Composition API:

In the child component:

<script setup>


const emit = defineEmits(["updateItem", "updateCount"])


function itemizedLot() {
emit("updateItem", param1, param2)
}


function countedLot() {
emit("updateCount", param3, param4)
}


</script>


<template>
<button @click="itemizedLot"> Btn1 </button>
<button @click="countedLot"> Btn2 </button>
</template>

In the parent component:

<script setup>


// access the emitted methods and their parameters


function updateMenuItem(param1, param2) {
...
}


function updateMenuCount(param3, param4) {
...
}


</script>


<template>
<MyButton @update-item="updateMenuItem" @update-count="updateMenuCount"/>
</template>