[英]child component emit an custom event, but parent component's listener not triggered
我在 Vue 中注册了一个子组件,子组件会发出一个自定义事件,但没有触发父组件的侦听器。
<template id="add-item-template">
<div class="input-group">
<input @keyup.enter="addItem" v-model="newItem" >
<span class="input-group-btn">
<button @click="addItem" type="button">Add!</button>
</span>
</div>
</template>
<div id="app" class="container">
<h2>{{ title }}</h2>
<add-item-component v-on:itemAdd="addAItem"></add-item-component>
</div>
Vue.component('add-item-component', {
template: '#add-item-template',
data: function () {
return {
newItem: ''
};
},
methods: {
addItem() {
this.$emit('itemAdd');
console.log("itemAdd In add-item-component");
}
}
});
new Vue({
el: '#app',
data: {
title: 'Welcome to Vue'
},
methods: {
addAItem: function () {
console.log("In #app, addAItem()!");
}
}
});
“itemAdd In add-item-component”日志显示在控制台中,但“在#app中,addAItem()!” 不要登录,#app 的方法 addAItem 没有被调用。
问题是自定义事件不应以驼峰命名。 如果您查看控制台中的错误消息,它会告诉您:
事件“itemadd”在组件中发出,但处理程序为“itemAdd”注册
即使您已使用驼峰命名法,该组件仍发出小写版本。 重命名为所有小写或 kebab-case 将修复它。
在父模板中:
<add-item-component @itemadd="addAItem">
从孩子发出:
this.$emit('itemadd');
在这里与 Evan You(Vue 创造者)讨论了一点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.