Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How listen to all events from one component in VueJS?

Tags:

vue.js

vuejs2

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>                                                                     
like image 579
Karolius Avatar asked Mar 16 '19 17:03

Karolius


People also ask

How do I listen to Vue events?

Listening to Events We can use the v-on directive, which we typically shorten to the @ symbol, to listen to DOM events and run some JavaScript when they're triggered. The usage would be v-on:click="handler" or with the shortcut, @click="handler" .

What does $emit do in Vue?

Vue $emit is a function that lets us emit, or send, custom events from a child component to its parent. In a standard Vue flow, it is the best way to trigger certain events.


2 Answers

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

like image 105
tony19 Avatar answered Oct 24 '22 04:10

tony19


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.

like image 35
Radu Diță Avatar answered Oct 24 '22 04:10

Radu Diță