16

I have 2 components: Post and Comments.

Inside Post component, there is Comments component that has 3 props: postId, numCom (number of comments) and comments (array).

I get comments and I pass the array with props, and now I want to retrieve the array in Comments component and add it to data so I can then add/remove comments etc.

Here is my code in Comments.vue:

props: ['id', 'numCom', 'comments'],
data: function() {
  return {
     newMessage: "",
     loading: false,
     allComments: this.comments,
     num: this.numCom,
   }
},

But this doesn't works. In Vue developer tools I can see that comments prop is filled with comments, but allComments array is empty.

What should I do?

eriel marimon
  • 1,230
  • 1
  • 19
  • 29
Miha Vidakovic
  • 393
  • 1
  • 4
  • 13
  • Are you sure that the `comments` prop has a value at the time the component is created? – Decade Moon Jul 10 '17 at 22:55
  • We'll need to see more code because I threw together an example and its working for me. https://jsfiddle.net/7xxwq1e2/18/ – Stephen Gilboy Jul 10 '17 at 22:57
  • @DecadeMoon yeah, there is a little delay, because I am doing GET request, then filling the props... How should I solve this? I could do a GET request inside Comments component, but how could I trigger a function in Comments component from Post controller when I display a new post? – Miha Vidakovic Jul 10 '17 at 23:01

3 Answers3

19

It looks like the comments prop does not have a value at the time of the component's creation (which is the only time allComments will be set).

You can either:

  1. Defer the creation of the component until the comments prop is ready by using v-if like this:
<comments v-if="comments" :comments="comments"></comments>
  1. Watch for changes to the comments prop and set allComments to the new value (in addition to initializing allComments in the data function):
watch: {
  comments(value) {
    this.allComments = value;
  }
}
Decade Moon
  • 32,968
  • 8
  • 81
  • 101
0

Use computed properties

computed: {
  allComments () {
    return this.comments
  }
}
Florin Miu
  • 46
  • 2
0

You dont need to put the props into data, just use this[propName] to get the value.

If you want to change a prop value or key to another value,just use computed to change it.

radiorz
  • 1,459
  • 4
  • 18
  • 36