0๐
Do you mean something like:
if (!this.answers.find(a => a.id === answer.answer_id)) {
this.answers.push(/* ... */);
}
- [Vuejs]-How to get the current Elastic APM instance in Vue.js?
- [Vuejs]-Vue โ How to import components dynamically
0๐
What you are doing is more or less right. There is no escape from the loop. However, there are certain things you can improve upon. Instead of forEach
, you can use Array.some
method. Alternately, you can use Array.find
method:
eventBus.$on('answer-added', answer => {
// Instead of using forEach, you can use Array.some() method
const answerExists = this.answers.some((x) => e.id == answer.answer_id);
if (!answerExists) {
this.answers.push({
id: answer.answer_id,
answer: answer.answer_text
});
}
});
Second, there is no problem with using an event bus, but it is generally used for a sibling or cross-component communication. When all the components are in the same ancestor or parent hierarchy, using
$emit
for events is the right way.
In your case, even though you have a nested components hierarchy, as the application evolves, a hierarchy can get really deep and you will quickly lose the track of typical publish-subscribe mechanism of the event bus. Even if it means re-emitting the same events from intermediate components, you should follow this practice.
- [Vuejs]-$emit event is not being heard in Vue components
- [Vuejs]-How to make the fields independent?
0๐
For anyone who comes across with the same issue, the problem I encountered is resolved by using a Simple Global Store. Other more complex scenarios would possibly require Vuex as suggested by @Dan above.
0๐
Pass a callback from parent to child. Now they can communicate bottom up. The child can pass any data the parent might want and then the parent can take back control and use its state or closure state.