Search code examples
javascriptvue.jsvuejs3event-handlingvue-component

Event error: TypeError: Cannot read properties of undefined (reading 'stopPropagation')


I can't use click modifiers when passing up the click event from a child component to the parent component. Does anyone know what I may be doing wrong here?

I have a component like this:

<!-- ButtonComponent -->
<template>
  <button @click="$emit('click')">Click Me</button>
</template>

<script setup>
</script>

And I'm using it like this:

<template>
  <ButtonComponent @click="doSomething()" />
</template>

When I try to apply the stop modifier, however:

<ButtonComponent @click.stop="doSomething()" />

I get the following error:

[Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'stopPropagation')"

SandBox Example

Bonus: I'd rather not manually emit events from the child component. Instead, I'd rather the child component forward all events to the parent component.


Solution

    1. The click handler is assigned to the root element due fallback attributes, so;
    <button>Click Me</button> 
    
    1. The error happens because .stop modifier actually assigns an extra handler that expects an object with stopPropagation method, pass the $event special variable, that will be handled by this extra handler:
    <button @click="$emit('click', $event)">Click Me</button> 
    
    1. Using the explicit $event is useful though with multiroot components:

    VUE SFC PLAYGROUND

    <script setup>
    const $emit=defineEmits(['click']);
    </script>
    
    <template>
      <button @click="$emit('click', $event)">Click Me</button>
      <div>I'm a multiroot component</div>
    </template>