6

I'm learning about Vuejs event handling.
I think that the developer could use this.$on('event', handler) in js file to process the 'event'.

There is an example.

<div id="mainapp" v-on:event="processEventFromView">
    <button type="button" v-on:click="emitEvent">
       Emit Event
    </button>
</div>

js File

var app = new Vue({
  el:"#mainapp",
  data:{
    show:false
  },
  created:function(){
     this.$on('event', this.processEvent);
  },
  methods:{
      emitEvent:function(){
          this.$emit('event', {data:'mydata'});
      },
      processEvent(data){
         console.log('js', data);  //this is fired when clicking the button.
      },
      processEventFromView(data){
         console.log('view', data);  //this is not fired whenever.
      }      

   }
})

But in the example, only the handler,processEvent, attached by this.$on() is fired when clicking the button. What is the difference between v-on vs this.$on?
Why is v-on:event="processEventFromView" not called whenever?
Could I attach the event handler to the click event of the button with reference, ref, instead of v-on:click="emitEvent"?
Please help me what I'm wrong.

tony19
  • 125,647
  • 18
  • 229
  • 307
Andrew Li
  • 1,005
  • 12
  • 29
  • I think (can't prove it yet) that Vue event emitting only traverses the component hierarchy and not the DOM. – Phil Oct 26 '18 at 02:55
  • 2
    For some perspective you can refer to [this issue](https://github.com/vuejs/vuejs.org/issues/1802). – Husam Ibrahim Oct 26 '18 at 03:08

1 Answers1

1

I guess it's related and answered by Linus Berg of Vue here https://stackoverflow.com/a/36159698/1225266 Although it's related to an earlier version of Vue (the post is from 2016) I guess it still applies.

In short the answer to your question

Why is v-on:event="processEventFromView" not called whenever?

is (I quote)

cannnot use v-on:custom-event-name in the template (that's only to be used on components).

softbear
  • 485
  • 6
  • 16
  • @tony19 Have you tried w a _custom_ event where you emit the event with this.$emit like in OP, then it doesn't work. (@click is a 'standard dom event'). – softbear Oct 27 '18 at 08:21
  • @tony19 still you're using v-on:custom in the component tag (which should work as stated by Linus Berg), and not in the template of the component which emits the event. – softbear Oct 28 '18 at 13:20