[Vuejs]-What's the right approach to update a parent's component array of objects from a child component?

0๐Ÿ‘

Do you mean something like:

if (!this.answers.find(a => a.id === answer.answer_id)) {
    this.answers.push(/* ... */);
}

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.

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.

Leave a comment