0

I have the following nested components structure:

<question>
    --> <answer>
        --> <best-answer-button>
    --> <answer>
        --> <best-answer-button>
    --> <answer>
        --> <best-answer-button>

There can be multiple questions on the page. Each question can have multiple answers.

Now, when an answer is marked as best, I need to:

  • let the parent <question> know, to add a "best answer" label or take it off
  • let all the sibling <answer>-s know

The point is, that I have to manipulate the question related to the <best-answer-button> and all of the question's <answer>-s, but I should not "touch" any other questions and answers on the page.

Is there a smooth way to fire an event from the <best-answer-button> component only to its respective <question>?

lesssugar
  • 15,486
  • 18
  • 65
  • 115
  • 1
    I'm trying to understand your app. Is it something like this? https://codepen.io/Kradek/pen/MrrQYm?editors=1010 – Bert Jan 08 '18 at 14:51
  • @Bert That's exactly it. One extra thing is when an answer is marked as "best", the respective question gets a "Best answer" label. – lesssugar Jan 08 '18 at 14:58
  • You can fork the pen to give an idea of what you mean there. I'm not sure I understand why a question would have a best answer label. – Bert Jan 08 '18 at 15:00
  • Sorry, I meant "Answered" - that's the label name when an answer is chosen. – lesssugar Jan 08 '18 at 15:01
  • 1
    I updated the pen. Is that right? I'm not necessarily recommending this as the way to do it, its just one way you could. – Bert Jan 08 '18 at 15:03
  • OK, so you're basically re-emitting the event up through both parents (answer and question). I was considering it but hoped there's something cleaner I could use. The solution is valid, though, and that's what I will end up doing in the end, so thank you very much for the time spent on it. – lesssugar Jan 08 '18 at 15:09
  • Sure there are other ways. I'm working on an example. – Bert Jan 08 '18 at 15:09
  • 1
    Here is the idiomatic way to do it with Vuex. https://codepen.io/Kradek/pen/RxxQGz?editors=1010 – Bert Jan 08 '18 at 15:16
  • I'm not experienced in the Vuex state management yet. May be the time to change that :) – lesssugar Jan 08 '18 at 15:17
  • 1
    This question is marked as a duplicate of another question I answered in the past, where my accepted answer shows a kind of non Vue way to emit from a child to a grandparent. I probably would lean toward a more Vuex like approach these days. I often feel like Vuex is overkill for a small project, but I'm increasingly in the minority with that opinion :) Of course probably as a last resort you can always use an Event Bus. This is all covered in the non parent child communication section of the documentation. – Bert Jan 08 '18 at 15:21

0 Answers0