Parent listen to child emit event in Vuejs

Asked By: Anonymous

Is there a way for the parent component listen to its child component emmited custom event?

// -- child comp
const addnewbtn  = {
    template : '<div><button v-on:click="showform">Add New Task</button><form v-show="form" v-on:submit.prevent="addnewtask"><input type="text" v-model="taskname" /><button>Add</button></form></div>',
  data(){
    return {
        taskname : '',
      form : false
    }
  },
  methods : {
    showform(){
        if( this.form ){
        this.form = false;
      }else{
        this.form = true;
      }
    },
    addnewtask(){
      this.$emit('add-task',this.taskname);
    }
  },
}

// -- parent comp
Vue.component('todolist',{
    components : { addnewbtn },
    data(){
    return {
        todoitems : [
        { name : 'Task 1', checked : false },
        { name : 'Task 2', checked : false },
        { name : 'Task 3', checked : false },
      ]
    }
  },
  methods : {
    makeitdone(item){
        if( this.todoitems[item].checked ){
        this.todoitems[item].checked = false;
      }else{
        this.todoitems[item].checked = true;
      }
    },
    removeitem(item){
        this.todoitems.splice(item,1);
    },
    addtask(){
        alert();
    }
  },
  created(){
    this.$root.$on('add-task',function(){
        alert();
    });
  }
});

tried

this.$root.$on('add-task',function(){
  alert();
});

or

this.$parent.$on('add-task',function(){
  alert();
});

but unfortunately, neither from two works. How can I do this?


Solution

Answered By: Anonymous

In your parent component, simply adding listen @add-task

<addnewbtn @add-task="addtask" />

then it can listen for the event which is emitted from children

  this.$emit('add-task',this.taskname);

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen Windows 10 Lisans Office 2019 Mac Satın Al follower kaufen instagram follower kaufen porno