0

As briefly as I can put it, I have a main <App /> component that houses a <CommentList /> component.

The <CommentList /> contains a number of <Comment /> components, more of which are added dynamically.

In my <App /> I have a listener for when a comment is added like so:

// App.vue
mounted() {
    this.$on('comment-added', console.log('wow'))
}

and the event is emitted from the <Comment /> component (grand child, if that matters?)

// Comment.vue
mounted() {
    console.log('this works for each comment no problem')
    this.$emit('comment-added') // this only ever works 1 time
}

The problem is the listener in the <App /> mounted function is only ever called once, even after subsequent comments are added to the list.

I don't understand why, any ideas? Been looking through the docs and searching but can't find any reason why this is happening.

Thanks!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
shanehoban
  • 870
  • 1
  • 9
  • 30

1 Answers1

0

I recommend to use inject/provide to make interaction between grandparent and grandchild component

App.vue

provide(){
return {
    addComment: this.addComment
  }
},
methods:{
    addComment(){
     console.log('wow')
   }
}
// Comment.vue

inject:['addComment'],
mounted() {
   this.addComment()
 
}
tony19
  • 125,647
  • 18
  • 229
  • 307
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164