[英]using $emit multiple times separated by setTimeout in vue not working as expected
I am firing a function in vue that emits a value of true or false to the parent.我正在 vue 中触发一个函数,该函数向父级发出 true 或 false 值。
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).如果我删除 setTimeout() 之外的第一个 $emit(返回 true),父级将正确显示第二个 $emit(setTimeout 内)(带有 false 值)。
In summary, I am having trouble with an $emit and then firing the same $emit (or overriding it?) once I am inside setTimeout.总之,我在使用 $emit 时遇到了麻烦,然后在我进入 setTimeout 时触发了相同的 $emit(或覆盖它?)。
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控制台正确记录: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控制台正确记录: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控制台只记录: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.发生的事情是我使用“passed_value”来切换一个 div,而这个 div 里面有这个组件。 When the 'passed_value' was set to false the div including the component were gone, therefore the communication with the component was lost.当“passed_value”设置为 false 时,包含组件的 div 消失了,因此与组件的通信丢失。 I changed v-if to v-show in the wrapper div so that the component stayed in the DOM, just hidden.我在包装器 div 中将 v-if 更改为 v-show,以便组件保留在 DOM 中,只是隐藏。
<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!感谢大家的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.