How to get recurring component event to parent in Vue

So I have a Commentbox component that lists user comments (Comment) in a nested parent-child hierarchy using recursion.

// Commentbox.vue (child)
<template>
   <comment :comments="comments"></comment-box>
</template>

let’s assume the data passed to this child component is

[
  { id: a, parent: c, children: [], comment: cdoisdskds ....}
  { id: b, parent: a, children: [...,...], comment: bjdskdls .... }
]

and then in the child component itself, we have a code structure like below:

<template>
   <div v-for="(comment, index) in comments" :key="index" >

      <div  v-if="comment.children" @click="this.$emit('repling', somedata )" > is parent layout </div>
      <div v-else >

        //is child - do the parent-child check layout etc...
        <comment :comment.children></comment>

      </div>
   </div>
<template>

The layout works great with no issues but the problem occurs when I try to emit an event from child to parent.

It works in the parent component as such and I can successfully get the event for the immediate children…

<comment-box>
  <comment @replying="dostuff"></comment>
</comment-box>

The problem lies when I click the child components, since its a recurring component, one would expect that it behaves the same way but it doesn’t. The event doesn’t resonate to the parent component.

How can this edge case be handled in vue?

Answer

You should pass down the $listeners from parent to children, or re-emit even to back from children to parent. Easiest way is to do add v-on="$listeners" when you start recursing the component:

<template>
   <div v-for="(comment, index) in comments" :key="index" >

      <div  v-if="comment.children" @click="$emit('replying', somedata)" > is parent layout </div>
      <div v-else >
        <comment v-on="$listeners" :comment.children></comment>
      </div>
   </div>
<template>

See the v-on="$listeners" addition.