Home » vue » vue.js prop array/object vs literal

vue.js prop array/object vs literal

Posted by: admin November 26, 2021 Leave a comment

Questions:

Props in vue.js are one way binding, by the way,in the documentation :

https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow

“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 will affect parent state.”

So i want to know, the prop.sync is it only for “litteral” (ie; string, number,date) or I must use it also with object/array ?

I already use object WITHOUT sync and all work very well, but i am fear it is not the good solution for do “vue.js” way ?

SO my question is : can i use object/array in prop,without sync, with no problem ?

Answers:

In some cases, we may need “two-way binding” for a prop. Unfortunately, true two-way binding can create maintenance issues, because child components can mutate the parent without the source of that mutation being obvious in both the parent and the child.
That’s why instead, we recommend emitting events in the pattern of update:myPropName. For example, in a hypothetical component with a title prop, we could communicate the intent of assigning a new value with:

this.$emit('update:title', newTitle)

You’ll get errors if you mutate a prop directly in a child component. So in that sense, no it’s not safe. The reason being is the parent will override anything the child sets.

###

Yes you can use objects and arrays as prop values. One difference, however, is when providing a default value for props of type object or array, you must define a factory function to return the default value.

The, main difference is the sync modifier is syntactic sugar that expands to a v-on listener. The child component emits events back the parent when a value changes, allowing the parent to update accordingly.

The child component must explicitly emit the event.

// example from docs
this.$emit('update:foo', newValue)