Skip to content
Advertisement

Passing dynamic boolean props to a VueJS component

How can I attach dynamic properties to a VueJS Component using VuetifyJS?

I have the following VuetifyJS code example that creates a select field element:

<div id="app">
  <v-app id="inspire" style="padding: 10px; ">
    <v-select 
      v-model="selectField"
      :items="items" 
      multiple attach chips>  
    </v-select>
  </v-app>
</div>

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      selectField: '', 
      items: [
        'item1', 
        'item2', 
        'item3'
      ],
      booleanProperties: [
        'multiple', 
        'attach', 
        'chips'
      ]
    }
  },
})

This creates a functional VuetifyJS select component, however I want to know how to pass the boolean props multiple, attach, chips to the select element as data properties so they do not have to be specified explicitly in the component declaration.

For example: I want to add the props: multiple, attach, chips defined within the data array element booleanProperties while still being able to define the component without having them specified. This way it works dynamically for any prop I pass.

Something similar to the following pseudocode example.

<v-select 
    v-model="selectField"
    :items="items"
    v-for="(booleanProperties) as boolProp">         
</v-select>

How can I pass/specify the data props: multiple, attach, chips dynamically for the v-select element?

Here is a code example of what I am referring to. https://codepen.io/deftonez4me/pen/NWRLWKE

Advertisement

Answer

You can simply use v-bind without specifying the key/property, and then passing an object into it, i.e. v-bind="additionalProps". As per VueJS v2 documentation on v-bind:

When used without an argument, can be used to bind an object containing attribute name-value pairs.

You can also merge your items binding into the object returned by additionalProps then, for brevity. Example based on your code.

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      selectField: '', 
      additionalProps: {
        items: [
          'item1', 
          'item2', 
          'item3'
        ],
        multiple: true,
        attach: true,
        chips: true
      }
    }
  }
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/vuetify/2.3.16/vuetify.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/2.3.16/vuetify.min.js"></script>
<div id="app">
  <v-app id="inspire" style="padding: 10px; ">
    <v-select 
      v-model="selectField"
      v-bind="additionalProps">  
    </v-select>
  </v-app>
</div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement