Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array as prop for Vue.js component?

Tags:

vue.js

I have a glorified input component called 'field', in which I have declared a number of props, thus:

 props: ['value','cols','label','group','name']

Given that this is effectively a fancy wrapper for an input, there are quite a few other attributes I might want to pass in as well, such as 'placeholder', for example. I don't really want to have to declare all of these in props (although the list is finite enough for it to be possible to do so, of course). What I'd prefer to do is to pass an array, perhaps called 'attrs', which could contain an arbitrary set of properties. Now I know it's possible to do this, but my question is how would I create this from within the parent? Can I do so with something like the following (although obviously with the requirement for bindings)?

 <field :attrs="['placeholder':'Whatever','length':42]"></field>
like image 218
John Moore Avatar asked Nov 24 '16 18:11

John Moore


1 Answers

that's an object not an array and yes it's fine to pass objects as props. Just set the values within the parent components data object, i.e.

data() {
  return {
    attributes: { 
      placeholder: 'Whatever',
      length: 42,
    },
    ...
  }
}

and bind this as your prop:

<field :attrs="attributes"></field>

To clarify - it is possible to set objects / arrays etc directly within the template, vue's template parser will then set the values on the relevant props, i.e.

<field :attrs="[{ name: 'foo' }, { name: 'bar' }]"></field>

However it is not a best practice as your templates soon get messy and it can become harder to determine where data is being set. Instead it is recommended that you abstract this data to a param on the component and bind that param to the prop - as above.

like image 131
GuyC Avatar answered Nov 16 '22 17:11

GuyC