'VueJS2 how to dynamically emit event to parent component?

just like the title i need to dynamically emit an event to parent component's methods, i have a component structured like this

<TableComponent 
  :actionmenus="actionmenus"
  @edit="parenteditmethod"
  @delete="parentdeletemethod">
</TableComponent>

here is actionmenus object

actionmenus: [
  {title: 'Edit', emitevent: 'edit'},
  {title: 'Delete', emitevent: 'delete'}
]

and then here is snippet of my tablecomponent

...
<ul>
  <li v-for="menu in actionmenus"><a @click="$emit(menu.emitevent)" class="text-menu">{{ menu.title }}</a></li>
</ul>
...

i know this should be easily done by $emit('edit') or $emit('delete') without using actionmenus object but the $emit() part should be dynamic based on the passed array actionmenus so that the tablecomponent can be re-used on different case. how should i approaching this? is there any way?



Solution 1:[1]

@codincat is right, that it all works. It's true also for Vue3

const rootComponent = {
  el: "#app",
  data: function () {
    return {
      actionmenus: [
        { title: "Edit", emitevent: "edit" },
        { title: "Delete", emitevent: "delete" }
      ]
    };
  },
  methods: {
    parenteditmethod() {
      console.log("edit");
    },
    parentdeletemethod() {
      console.log("delete");
    }
  }
};

const app = Vue.createApp(rootComponent);
app.component("table-component", {
  props: { actionmenus: Array },
  template: `
    <ul>
      <li v-for="menu in actionmenus">
        <a @click="$emit(menu.emitevent)" class="text-menu">{{ menu.title }}</a>
      </li>
    </ul>`
});

const rootComponentInstance = app.mount("#app");
<!-- https://stackoverflow.com/questions/43750969/vuejs2-how-to-dynamically-emit-event-to-parent-component -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.29/vue.global.min.js"></script>

<div id="app">
  <table-component :actionmenus="actionmenus" @edit="parenteditmethod" @delete="parentdeletemethod">
  </table-component>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1