VueJS right way to edit prop without changing parent data

前端 未结 4 1318
傲寒
傲寒 2020-12-14 21:21

In my parent vue component I have a user object.

If I pass that user object to a child component as a prop:

         


        
4条回答
  •  情书的邮戳
    2020-12-14 22:13

    According to this, children "can't" and "shouldn't" modify the data of their parents. But here you can see that if a parent passes some reactive data as a property to a child, it's pass-by-reference and the parent sees the child's changes. This is probably what you want most of the time, no? You're only modifying the data the parent has explicitly shared. If you want the child to have an independent copy of user, you could maybe do this with JSON.parse(JSON.stringify()) but beware you'll be serializing Vue-injected properties. When would you do it? Remember props are reactive, so the parent could send down a new user at any time, wiping out local changes?

    Perhaps you need to tell us more about why you want the child to have it's own copy? What is the child going to do with its copy? If the child's user is derived from the parent user in some systematic way (uppercasing all text or something), have a look at computed properties.

提交回复
热议问题