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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With