Skip to content
Advertisement

How to get props value to be used in emits array

I got a console error when I tried to list custom event in the component’s emits option like this:

PARENT

<Btn
   event-name="toggleSideMenu"
   @toggle-side-menu="toggleHandler">
        toggle
 </Btn>

CHILD

<template>
   <button @click="handleClick">
      <slot></slot>
   </button>
</template>

export default {
   props: {
      eventName: {
         type: String,
         default: ''
      }
   },
   emits: [this.eventName], // Uncaught TypeError: Cannot read property 'eventName' of undefined
   methods: {
      handleClick() {
          this.$emit(this.eventName)
      }
   }
}

How is the correct way to get this thing to work?

Advertisement

Answer

I don’t think you’ll be able to do that.

You may need to find a way to get around this. You can still emit an event without defining it in the emits array, but you end up losing some of the benefits.

There is an RFC/proposal for doing just that, but doesn’t look like it’s going anywhere.

Advertisement