An array as a support for the Vue.js component?

I have an illustrious input component called a "field" in which I declared a few details, like this:

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

Given that this is a really attractive input wrapper, there are quite a few other attributes that I might want to pass, for example, "placeholder". I really do not want to declare all this in the details (although the list is large enough to be possible, of course). What I would prefer to do is pass an array, possibly called an "attrs", which can contain an arbitrary set of properties. Now I know that this is possible, but my question is how can I create this from within the parent? Can I do this with something like the following (although obviously with a binding requirement)?

 <field :attrs="['placeholder':'Whatever','length':42]"></field>
+4
source share
1 answer

that the object is not an array, and yes, it’s fine to pass objects as props. Just set the values ​​in the data object of the parent components, i.e.

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

and tie it as your footing:

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

To clarify - you can set objects / arrays, etc. directly in the template, vue template parser will then set the values ​​in the corresponding details, i.e.

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

However, this is not best practice, as your templates will soon become messy, and it may be more difficult to determine where the data is installed. Instead, it is recommended to abstract this data with a parameter on the component and bind this parameter to prop - as described above.

+4
source

Source: https://habr.com/ru/post/1661879/


All Articles