Home » vue » What are some alternatives in vue.js to passing data to child components other than props

What are some alternatives in vue.js to passing data to child components other than props

Posted by: admin November 26, 2021 Leave a comment

Questions:

I know the correct pattern to pass data from/to a parent/child component in vue.js is to pass props from the parent to the child and emit events from the child to the parent. But is there anything wrong with this:

this.$refs['child-component'].setValue(val)

I’m told that one should use refs to access child components sparingly, and only when there is no other way.

What if I want to update the value of a field in an array in the child component that isn’t bound to a prop, something like this:

this.$refs['child-component'].childArray[index] = val;

…where childArray is not a prop of child-component? Do I need to MAKE childArray a prop of child-component? But then it becomes the parent’s responsibility to maintain childArray. What if it isn’t the business of the parent component to maintain childArray?

Thanks.

Answers:

Actually, it is not a business of the parent to mess with the child’s internal data at all. You should not directly mutate internal data of a child – instead, consider calling a method or emitting an event (which should be handled by the child).

Currently you are creating a tight coupling between the parent and the child – now the parent is overloaded with knowledge about the child internals. Tomorrow, when you decide to change the implementation of the child (for whatever reason) – most probably you will also have to inspect all parents where this child is being used just to check that your changes did not break the assumptions of those parents.