问题 Vue.js将道具传递给数据


我有2个组件: Post 和 Comments

在Post组件中,有一个包含3个道具的Comments组件: postIdnumCom (评论数量)和 comments (阵列)。

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

这是我的代码 Comments.vue

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

但这不起作用。在Vue开发人员工具中我可以看到 comments 道具充满了评论,但是 allComments 数组是空的。

我该怎么办?


5757
2017-07-10 22:38


起源

你确定吗? comments prop在组件创建时有一个值? - Decade Moon
我们需要看到更多的代码,因为我把一个例子和它为我工作。 jsfiddle.net/7xxwq1e2/18 - Stephen
@DecadeMoon是的,有一点延迟,因为我正在做GET请求,然后填充道具......我应该如何解决这个问题?我可以在Comments组件中执行GET请求,但是当我显示一个新帖子时,如何在Post控制器的Comments组件中触发一个函数? - Learn Css


答案:


它看起来像 comments prop在组件创建时没有值(这是唯一的时间 allComments 将被设定)。

你可以:

  1. 推迟创建组件直到 comments 道具已准备就绪 v-if 喜欢这个:
<comments v-if="comments" :comments="comments"></comments>
  1. 注意改变 comments 道具和设定 allComments 到新值(除了初始化 allComments 在数据函数中):
watch: {
  comments(value) {
    this.allComments = value;
  }
}

13
2017-07-10 23:12