简体   繁体   English

Vue - 动态组件事件监听器

[英]Vue - Dynamic component event listener

Problem : I am trying to create a table component for my app which would be use by other components to render a table.问题:我正在尝试为我的应用程序创建一个table组件,其他组件将使用它来呈现表格。 It could have three possible cell values :它可能有三个可能的单元格值:

  • Text文本
  • HTML HTML
  • Component成分

I am able to render all the above values but I am stuck at binding an event listener.我能够呈现上述所有值,但我坚持绑定event侦听器。 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表 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.如果需要更多信息,请告诉我。

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父.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) {
  }
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM