如何评估data属性中的Vue.js组件道具?

Mih*_*vic 15 javascript vue.js vue-component vuejs2

我有2个组件:PostComments.

在Post组件中,有一个Comments组件有3个props:postId,numCom(注释数)和comments(数组).

我得到了注释,并使用props传递数组,现在我想在Comments组件中检索数组并将其添加到数据中,以便我可以添加/删除注释等.

这是我的代码Comments.vue:

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

但这不起作用.在Vue开发人员工具中,我可以看到commentsprop填充了注释,但allComments数组为空.

我该怎么办?

Dec*_*oon 18

看起来commentsprop在组件创建时没有值(这是唯一的allComments设置时间).

你可以:

  1. 推迟组件的创建,直到comments支柱准备就绪,使用v-if如下:
<comments v-if="comments" :comments="comments"></comments>
Run Code Online (Sandbox Code Playgroud)
  1. 监视commentsprop的更改并设置allComments为新值(除了allComments在数据函数中初始化):
watch: {
  comments(value) {
    this.allComments = value;
  }
}
Run Code Online (Sandbox Code Playgroud)