How to evaluate Vue.js component props in the data property?

Viewed 12783

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?

3 Answers

Use computed properties

computed: {
  allComments () {
    return this.comments
  }
}

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.

Related