Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue best practice, props object or primitive types?

Tags:

vue.js

Vue support both primitive types and object as props to pass them from parent to its child.

I ever heared that it is a best practice to always pass primitive types instead of passing an Object. Maybe it is because the primitive types are easy to detect if changed.

Is it true? Is it a best practice or just something dumb?

like image 631
Hank Avatar asked Oct 22 '18 14:10

Hank


People also ask

Are Vue Props required by default?

All props are optional by default, unless required: true is specified. An absent optional prop other than Boolean will have undefined value. The Boolean absent props will be cast to false .

Why Props are used in Vuejs?

In summary, we use props to pass down data from the parent components to the child component(s). The child component also emit events to the parent component(s) in case you need to send data/events from the child to the parent component.

Are Vue Props reactive?

Props and data are both reactiveWith Vue you don't need to think all that much about when the component will update itself and render new changes to the screen. This is because Vue is reactive. Instead of calling setState every time you want to change something, you just change the thing!

What should be a component Vue?

Vue components are written as a combination of JavaScript objects that manage the app's data and an HTML-based template syntax that maps to the underlying DOM structure.


1 Answers

There is no real "best practice" at it really depends on what you're trying to accomplish.
You can use both really, but remember when passing non-primitives you're passing a POINTER, not the actual object. Thus, when modifying said object inside the child, you will also modify the original object.

If you're going to pass around objects, that you want to MODIFY, but as a "copy", you can always pass them using the expand operator to create a copy as such.

{ ...myObject }
[ ...myArray ]

<child-object :someprop="{...object}"></child-object>

That way you ensure that if you're going to modify the object at child level, the child owns a copy of this object and you're not getting unexpected behavior on the parent.

like image 154
Marina Mosti Avatar answered Oct 01 '22 11:10

Marina Mosti