[Vuejs]-Listening to custom events but set the code outside the component's HTML

0👍

You should emit the name of the event. In this case this.$emit("my-event", "a string value") ;

0👍

For the souls looking to add programmatically events to the parent component you can add it like this:

export default {
   name: testComponent,
   created(){
      this.$on("mycustomevent", this.customevent);
   },
  methods:{
    customevent(){
      alert("this is a custom event");
    }
  }  
}

then on the child component you can call the event like this (using for example:mounted() )

mounted(){
   this.$emit('mycustomevent');
}

this is usefull for Dynamic layout wrapper components since you cannot declare custom events for custom themes on App.vue in my case:

<template>
  <div id="app">    
      <component :is="layout">
          <router-view :layout.sync="layout"/>
      </component>
  </div>
</template>

which depend on a variable and must work for all templates or views (in my case layout)
now you can have your custom events started within the js code without the need to declare them in the js!

Leave a comment