I’ve been working with Vue for a little while now but there are still some basic things I don’t think I’ve fully sorted out in my head yet. One is to do with the issue of two-way data communication between parent and child components.
Where I’m getting confused over the correct approach is in a CRUD application, with listing and detail screens. I have a list of customers. When the user double clicks on one, the list is hidden and a data entry form is displayed in its place, with the details of the customer selected. So for this, I have a parent CustomerManager component, with ‘customer’ as one of its data fields, and two child components, CustomerList and CustomerDetail. Double-clicking on a row in CustomerList sets the values of the ‘customer’ object in CustomerManager. This is used as a prop in CustomerDetail, thus:
<customer-detail v-if="editMode==true" :customer="customer"></customer-detail>
Now, I’m aware that I shouldn’t directly mutate props in child objects, and if the customer prop for CustomerDetail were e.g., a string, I would get a warning when I attempted to do so. Because it’s an object in this case, though, I can mutate it without warning in the CustomerDetail component, and I can see the changes taking effect in the parent CustomerManager.
Is this bad practice? It achieves exactly what I want to achieve in as simple a way as I can. The customer object is effectively shared between components, and I do want it to be updated throughout when I make a change to it in one of the components.
The alternative, as I understand it, is cloning the prop as a data field in CustomerDetail (simply copying it to a data field from a prop doesn’t do anything as both prop and data versions would be references to the same object), using the cloned prop in the child component and when it is changed, doing an emit with the new value which is then picked up by a handler in the CustomerManager object, which duly updates the parent object. This seems to me to be rather cumbersome and longwinded and doesn’t offer me any compensating advantages.
What would others do in this situation?