[Vuejs]-Vue.js two way binding using a custom type

1πŸ‘

βœ…

I found the answer in Vue.js documentation on the "one way data flow" (https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow). They specify the following caveat:

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 one way data flow is not strictly enforced and there is no error or warning in this case. This is a loophole – (which is best avoided).

0πŸ‘

You’re able to modify the object because object references are values in Javascript – which makes objects act like they are passed by reference.

In other words:

Javascript always passes by value, but for arrays and objects the value is a reference to the object.

https://medium.com/nodesimplified/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c

It’s allowed because the alternative is copying the whole object (which could include nested objects and is not really practical).

Also, this is an opinion, but you should not do this.

-1πŸ‘

you can use Vue’s $emit feature to communicate between child/parent, more examples here :

https://v2.vuejs.org/v2/guide/components-custom-events.html

-1πŸ‘

I do not see a downside of using it, more than loosing the track where the object is modified in a very nested child components. I will play around a bit more with your codepen, I also wanna know why it is possible, and Avoid mutating a prop directly error is not raised.

Leave a comment