1
votes

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.

1

1 Answers

0
votes

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