I am firing a function in vue that emits a value of true or false to the parent.
This is the child component code:
methods: {
updateProduct(product){
//this fires properly and returns true
this.$emit('event_child', true);
//then I fire a setTimeout function
setTimeout(() => {
//do a bunch of tasks and then i attempt another emit
this.$emit('event_child', false);
//but the event_child does not update to false in the parent
}, 3000);
}
}
If I remove the first $emit outside of the setTimeout() (returning true) the parent will show the second $emit (inside setTimeout) correctly (with false value).
In summary, I am having trouble with an $emit and then firing the same $emit (or overriding it?) once I am inside setTimeout.
My parent looks like this:
<child-component v-on:event_child="eventChild" />
and the method:
methods: {
eventChild: function(passed_value) {
console.log('Event from child component emitted: ', passed_value);
}
}
For further clarification:
If I do this from the child:
this.$emit('event_child', true);
this.$emit('event_child', false);
this.$emit('event_child', true);
The console logs correctly: true, false true
If I do the following only:
setTimeout(() => {
this.$emit('event_child', true);
this.$emit('event_child', false);
this.$emit('event_child', true);
}, 3000);
The console logs correctly: true, false true
And when I do:
this.$emit('event_child', true);
this.$emit('event_child', true);
setTimeout(() => {
this.$emit('event_child', false);
this.$emit('event_child', false);
}, 3000);
The console only logs: true, true
I found the problem. Thanks to Dan's fiddle I realised that the question I asked actually did not produce any issues. What happened is that I was using the 'passed_value' to toggle a div, and this div had the component inside. When the 'passed_value' was set to false the div including the component were gone, therefore the communication with the component was lost. I changed v-if to v-show in the wrapper div so that the component stayed in the DOM, just hidden.
<div v-if="!this.passed_value">
<child-component v-on:event_child="eventChild" />
</div>
to:
<div v-show="!this.passed_value">
<child-component v-on:event_child="eventChild" />
</div>
Thanks to everyone for your assistance!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.