0
votes

I found it is possible to just pass an object to a component through props and bind and the child component can set keys on the object which is then available to the parent component.

So it appears that "emit" is not strictly required for passing data back to the parent component.

Am I missing something?

1

1 Answers

2
votes

Yes you can pass an object as a props and mutate it, however, it's considered as anti pattern by Vue because "Due to the new rendering mechanism, whenever the parent component re-renders, the child component’s local changes will be overwritten"

Generally you shouldnt do that. This can / could cause unexpected bugs in your code. Generally you should make a copy of your object, modify that, then emit upwards to the parent (as you have mentioned in your last paragraph I believe). This is the method I take and is the general consensus of top down, emit up approach.

Source: https://forum.vuejs.org/t/is-mutating-object-props-bad-practice/17448/2

On that discussion also mentioned that it "doesn’t have any real imminent risk in simple components.". I personally think it's okay to mutate your props directly from child in some suitable case.

But it's better to mutate a data from the parent component by emitting an event from your child component.

You can also use sync modifier to make two-way binding easier.


Not really related to your question, but this is also one of the deciding factor whether to store a data in Vuex or local state (at least for me). When I have a data that's shared to component's children, emitting and registering an event listener to the component can make my code a little bit messy. So I use Vuex instead to store the data and mutate it.

This is a nice decision flow chart I found from here about whether to store your data in Vuex or not. Vuex decision flow chart