简体   繁体   English

在子组件中改变数组道具是否有效?

[英]Is it valid to mutate an array prop in a child component?

I've noticed when pushing to an array that has been passed to a child component as prop, I don't get the usual 'Avoid mutating a prop directly' error.我注意到,当推送到作为道具传递给子组件的数组时,我没有得到通常的“避免直接改变道具”错误。 After thinking about it, this makes sense because the array is a reference and if something causes the parent to re-render, the child will render correctly because of this.仔细想想,这是有道理的,因为数组是一个引用,如果某些事情导致父级重新渲染,子级将因此正确渲染。

Is the proper approach still to emit to the parent and have the parent operate on the array, or is it perfectly valid to operate on the array in the child component since it is a reference?正确的方法仍然是向父级发出并让父级对数组进行操作,还是在子组件中对数组进行操作是完全有效的,因为它是一个引用?

According to the official docs on props :根据关于 props 的官方文档

Note that objects and arrays in JavaScript are passed by reference, so if the prop is an array or object, mutating the object or array itself inside the child component will affect the parent state and Vue is unable to warn you against this. Note that objects and arrays in JavaScript are passed by reference, so if the prop is an array or object, mutating the object or array itself inside the child component will affect the parent state and Vue is unable to warn you against this. As a general rule, you should avoid mutating any prop, including objects and arrays as doing so ignores one-way data binding and may cause undesired results.作为一般规则,您应该避免改变任何道具,包括对象和 arrays,因为这样做会忽略单向数据绑定并可能导致不希望的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM