0

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.

gib65
  • 1,709
  • 3
  • 24
  • 58

1 Answers1

2

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.

IVO GELOV
  • 13,496
  • 1
  • 17
  • 26
  • Awesome! Emitting events to children is one of the things I was looking for (though I didn't mention it in the OP). I found this: https://stackoverflow.com/questions/42632711/how-to-call-function-on-child-component-on-parent-events ... to explain how. – gib65 Jun 23 '20 at 21:48