如何评估数据属性中的 Vue.js 组件道具? [英] How to evaluate Vue.js component props in the data property?

查看:18
本文介绍了如何评估数据属性中的 Vue.js 组件道具?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组件:PostComments.

I have 2 components: Post and Comments.

在 Post 组件内部,有一个 Comments 组件,它有 3 个属性:postIdnumCom(评论数量)和 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.

这是我在 Comments.vue 中的代码:

Here is my code in Comments.vue:

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

但这行不通.在 Vue 开发者工具中,我可以看到 comments 道具充满了注释,但 allComments 数组是空的.

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

我该怎么办?

推荐答案

看起来 comments 属性在组件创建时没有值(这是唯一一次 allComments 将被设置).

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).

您可以:

  1. 使用 v-if 像这样推迟组件的创建,直到 comments 道具准备好:
  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. 观察 comments 属性的变化并将 allComments 设置为新值(除了在数据函数中初始化 allComments 之外):
  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;
  }
}

这篇关于如何评估数据属性中的 Vue.js 组件道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆