[Vuejs]-Calling a Vue 3 parent method based on the string payload of a child component's emitted event

0👍

You would basically have to go back to Options API which could dynamically call methods using their name like this[methodName]()

With Composition API no longer having access to this, a minimal workaround solution would involve wrapping your methods in an object that makes them callable in a similar way to Options API.

const dynamicMethods = {
  nextStep: () => {
    console.log('next step')
  },
  
  closeStep: () => {
    console.log('close step')
  },
  
  prevStep: () => {
    console.log('prev step')
  }
}
<ButtonBar @buttonClick="dynamicMethods[$event]()" />

Say you still want to call nextStep() elsewhere in your code and not have to always call it like dynamicMethods.nextStep(), you can still do that by destructuring dynamicMethods on a different line:

const { nextStep, closeStep, prevStep } = dynamicMethods

Now your methods are dynamically callable from the template with minimal changes to your script code.

Vue Playground example

Leave a comment