How listen to all events from one component in VueJS?

半世苍凉 提交于 2020-12-29 22:50:50

问题


Is there a possibility in Vue to deal with incoming events inside one function in a way similar to this?

<template>         
    <component v-on="eventsDistributor(eventName, $event)"/>                                                                 
</template>                                                                   
<script>                                                                      
export default {                                                                      
  props: {
      handlers: Object,
  },
  methods : {                                                                 
      eventsDistributor (name, $event) {                            
          let handler = this.handlers[name]
          if (handler) return handler($event)
      }                                                                       
  }                                                                           
}                                                                             
</script>                                                                     

回答1:


I think $listeners might be what you need. It's an object that contains all parent listeners, and it could be forwarded to children with v-on="$listeners".

For example, you have a <button> wrapper component, and you want any listeners on the wrapper to be bound to the button:

<!-- MyButtonWrapper.vue -->
<template>
  <button v-on="$listeners">Click</button>
</template>

<!-- Parent.vue -->
<template>
  <!-- click and mouseover listeners are bound to inner button -->
  <MyButtonWrapper @click="onClick" @mouseover="@mouseover" />
</template>

demo




回答2:


There is no standard way of achieving this.

The author of vuejs offers a hack to listen on all events here. He also explains that introducing regexp or other means of listening to more events will have a performance impact and will probably not do it.



来源:https://stackoverflow.com/questions/55199485/how-listen-to-all-events-from-one-component-in-vuejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!