Home > front end >  Vue - Dynamic component event listener
Vue - Dynamic component event listener

Time:11-17

Problem : I am trying to create a table component for my app which would be use by other components to render a table. It could have three possible cell values :

  • Text
  • HTML
  • Component

I am able to render all the above values but I am stuck at binding an event listener. What I am trying to achieve is something like this : Pass a method and event which is to be binded to the component and the table should bind that with respective cell. So for example :

TABLE JSON

{
   "cell-1":{
      "type":"html",
      "data":"<h4>text-1</h4>",
      "method": someMethod
   }
}

TABLE COMPONENT

  <tbody>
   <template>
      <tr>
         <td  >
            <span
               v-if="type == 'html'"
               v-html="data"
               v-on:click.native="$emit(someMethod)"
               v-on:click.native="someMethod"
               ></span>
         </td>
      </tr>
   </template>
</tbody>

Above is just a snippet of what I am trying, the table loops through the object passed and renders accordingly.

I have already tried

Please let me know if any more info is required.

CodePudding user response:

The best way is to have the method/handler inside the parent component and then trigger is using the emit functionality such that in

TABLE COMPONENT

  <tbody>
   <template>
      <tr>
         <td  >
            <span
               v-if="type == 'html'"
               v-html="data"
               v-on:click.native="$emit('trigger-handler', {method: 'method1', data: {}})"
               ></span>
         </td>
      </tr>
   </template>
</tbody>

and in

Parent.vue

<table-component @trigger-handler="triggerHandler" />

inside script

export default {
 data() {
 },
 methods: {
  triggerHandler(payload) {
   // payload is actually the object passed from the child
   this[payload.method](payload.data); // call a specific method
  },
  method1(data) {
  },
  method2(data) {
  },
  method3(data) {
  }
 }
}
  • Related