Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent listen to child emit event in Vuejs

Tags:

vue.js

vuejs2

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?

like image 324
Juliver Galleto Avatar asked Dec 23 '22 22:12

Juliver Galleto


1 Answers

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);
like image 166
ittus Avatar answered Jan 09 '23 22:01

ittus