Question

Typically the way to communicate between parent <-> child component in Vue.js is to send the child a prop and emit an event from the child, which is listened to on the parent.

However, if you pass in an object to a child prop, updating the object in the child will update the object in the parent as objects are passed by reference, not copied.

This basically provides two-way communication in a much simpler way, however, I never see this method referenced in any official tutorials. This suggests it may be an anti-pattern (you arent suppose to modify props in the child) but if it is, why? It achieves what I want. What could be the consequences of communicating in this way?

Was it helpful?

Solution

The Vue guide discourages prop mutation. The main reason it cites is that

whenever the parent component re-renders, the child component’s local changes will be overwritten

As you say, this problem does not apply to reference types, since those changes don't stay local to the component (assuming the prop is actually kept as part of the parent's state, and not generated on-demand). Indeed, the guide also says:

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 parent state.

So is it safe?

I would expect it to work just fine, functionally. Especially since it is documented behavior, I don't think it will change. However, doing this clearly falls under "prop mutation" conceptually, even if it is technically different. The guide discourages prop mutation. Other developers will not expect this behavior. Unexpected behavior causes bugs. And thus, any kind of prop mutation causes bugs, though sometimes indirectly.

Licensed under: CC-BY-SA with attribution
scroll top