简体   繁体   中英

child component emit an custom event, but parent component's listener not triggered

I'm registered a child component in Vue, the child will emit an custom event, but the parent component's listener not triggered.

<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()!");
    }
  }
});

The "itemAdd In add-item-component" log show in console, but "In #app, addAItem()!" log not, the #app's method addAItem not invoked.

The problem is that custom events should not be named with camelCase. If you look at the error message in the console, it tells you:

Event "itemadd" is emitted in component but the handler is registered for "itemAdd"

The component is emitting a lowercase version even though you've used camelCase to name it. Renaming to all lowercase or kebab-case will fix it.

In the parent template:

<add-item-component @itemadd="addAItem">

Emitting from the child:

this.$emit('itemadd');

This is discussed a bit with Evan You (Vue creator) here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM