Damon
Damon

Reputation: 4484

VueJS emitted event not getting picked up by parent component

I am struggling to understand why an emitted event on a child component is not getting picked up by the parent.

The event is getting emitted from the child component - I can see it in the toolbar along with the correct values. The method that is tied to the event is not getting called on the parent component. ChildComponent.vue is a form that is imported into ParentComponent.vue.

Here is what I have (that's working but not).

ParentComponent.vue

<child-component/>

<div v-show="this.label === 'acme'" @label:name="handleLabelName">
    <h3>Hello World</h3>
    ...
</div>

...

methods: {
    handleLabelName(name) {
        console.log('handleManualType called');  // never getting here
        console.log('name: ', name);             // never getting here
    }
},

ChildComponent.vue

...

<button data-label="acme" @click="handleClick($event)">Click Me</button>

...

methods: {
    handleClick(event) {
    const label = event.target.dataset.label;
    this.$emit('label:name', label); // acme
},

The event is getting broadcast, but handleLabelName is never getting called. I've read through this great article many times and I believe I'm following it correctly. Is there something I am doing wrong to make handleLabelName never get called? I've also tried wrapping everything in a div like so:

<div @label:name="handleLabelName">
    <div v-show="this.label === 'acme'">
        <h3>Hello World</h3>
        ...
    </div>
</div>

And still the same result. handleLabelName never gets called. I've also tried changing the event name/method to simple things like, foo and still no difference.

Thank you for any suggestions!

Upvotes: 4

Views: 3668

Answers (1)

spMaax
spMaax

Reputation: 395

You are listening for events on a div instead of listening to your child component. You must put your listener on the DOM element that sends the event. Try something like this :

<child-component @my-event-name="handleLabelName"/>

Another point is that you might prefer using kebab case to name your custom events. It might be a problem to name your event with this character ":" (see https://v2.vuejs.org/v2/guide/components-custom-events.html)

Upvotes: 6

Related Questions