custom event not caught in HTML Vuejs

Viewed 1575

I have an HTML partial like:

<div v-on:customevent="test">
   <button @click="launchEvent">TestEvent</button>
</div>

In my component I have this:

methods:{
   launchEvent(){
      this.$emit('customevent');
   },
   test(){
      console.log("I'm in");   
   }
}

But even tt runs correctly function launchEvent it doesn't launch function test as the event was not caught because the event is correctly launched because if I try set in created():

this.$on('customevent',function(){
   alert("customevent launched");
});

The alert is correctly launched, so, Is it possible listen custom event directly on HTML?

3 Answers

The syntax is incorrect in the first div, 'clicked' should be 'click', as in

<div v-on:click="test">Test Event</div>

or the short-hand syntax as used on the button,

<div @click="test">Test Event</div>

Edited after OP pointed that the answer wasn't working

Those events are meant to be used in a parent-child component relationship, as explained in the documentation

So, in your example, you should have a parent component catching the event and the child component emitting it.

Your parent will looks like :

<parent @custom-event="customEventCatched">
  <child></child>
<parent>

And your child component's template should be like :

<button @click="$emit('custom-event')">Emit<button>

My problem was that I not use correctly event:

now my code is:

<div>
   <MyComponent @customevent="eventCatched"></MyComponent>
</div>

And in MyComponent there is a function like:

test(){
   this.$emit("customevent");
}

In parent component I have a function eventCatched

eventCatched(){
  console.log("catched");
}

following this jsfiddle

https://jsfiddle.net/dangvanthanh/3m6s54qx/

Related