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

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

问题描述

我有2个组成部分: Post Comments .

I have 2 components: Post and Comments.

内部帖子组件中,有评论组件,它具有3个道具: postId numCom (评论数)和评论(数组)

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 中的代码:

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 设置为新值(除了在data函数中初始化 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;
  }
}

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

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