Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 2 - How to set default type of array in props

I have my Vue component, which is taking an array of objects as a prop. I often use prop validation, especially for 'default' value feature.

in this case I have:

props: {     items: Array } 

but I'd like it to have like in Typescript or React:

props: {     items: Array.of(         {key: {type: String, default: 'myText'}}         ) } 

etc.

Is it possible to achieve? Otherwise I need to use computed data as map just to set the defaults

like image 258
Łukasz Ostrowski Avatar asked Jan 09 '17 17:01

Łukasz Ostrowski


People also ask

Can you pass an array as a prop in Vue?

When objects and arrays are passed as props, while the child component cannot mutate the prop binding, it will be able to mutate the object or array's nested properties. This is because in JavaScript objects and arrays are passed by reference, and it is unreasonably expensive for Vue to prevent such mutations.

How do you use Props in Vue 2?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.

How do you mutate Props in Vue?

Mutating props in Vue is an anti-pattern In Vue, we pass data down the the component tree using props. A parent component will use props to pass data down to it's children components. Those components in turn pass data down another layer, and so on. Then, to pass data back up the component tree, we use events.


1 Answers

I created example: jsFiddle, that might can help you, and yes... you can return the default value as a array:

ES6

props: {     items: {         type: Array,         default: () => []     } } 
like image 158
t_dom93 Avatar answered Sep 27 '22 21:09

t_dom93