Sending variable boolean values to a VueJS component

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

Below is an example of VuetifyJS code that constructs 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 code snippet generates a functional VuetifyJS select component. However, my goal is to find out how to dynamically pass the boolean props multiple, attach, chips to the select element as data properties without explicitly specifying them in the component declaration.

For instance, I aim to include the props: multiple, attach, chips defined within the data array element booleanProperties while still being able to define the component without stating them. This approach allows for flexibility when passing any prop.

Here's a hypothetical example similar to what I am envisioning.

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

Is there a way to dynamically set the data props: multiple, attach, chips for the v-select element?

Check out this code example demonstrating the concept: https://codepen.io/deftonez4me/pen/NWRLWKE

Answer №1

To simplify the usage of v-bind, you can omit specifying the key/property and directly pass an object into it like so:

v-bind="additionalProps"
. As stated in the VueJS v2 documentation on v-bind:

When used without an argument, it can bind to an object that contains attribute name-value pairs.

You can also consolidate your items binding within the object returned by additionalProps for conciseness. Here's a relevant example based on your code snippet.

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>

Answer №2

If you want to keep things simple, you can use the following code snippet:

<div id="my-app">
  <v-app id="my-inspiration" style="margin: 20px; ">
    <v-select 
      v-model="selectedItem"
      :items="options" 
      :multiple="isMultiple"
      :attach="isAttachable"
      :chips="useChips">  
    </v-select>
  </v-app>
</div>

Next, make sure to define the props like so:

props: [
    'isMultiple', 
    'isAttachable', 
    'useChips'
]

Alternatively, you could be more specific with the prop declarations as shown below:

props: {
    isMultiple: {
        type: Boolean
    },
    isAttachable: {
        type: Boolean
    },
    useChips: {
        type: Boolean
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enumerate the variable values that are validated using jQuery

I've made good progress with this in jsFiddle, but I can't seem to figure out why the first value isn't displaying a bullet point.. Check out my code on jsFiddle! <div id="checkboxes"> <input id="chkbx_0" type="checkbox" name= ...

Having trouble performing an Image (base64) update in Next.js

Hi everyone, I'm facing a challenge with updating the image data in my code. The base64 string data updates correctly and the new image is displayed before submitting the data. However, once I submit the data, the image doesn't update. Below is ...

npm encountered an error due to an invalid query string passed to parseQuery. The proper format should include a question mark at the beginning

When I executed npm run build in my vue2 project, an error message appeared stating that loaderUtils.getOptions is not a function. After running cnpm install vue-loader vue-template-compiler loader-utils, I encountered the following error: ERROR in ...

What could be causing the return of undefined upon execution?

function updateTitle(title) { title = "updated title"; } var currentTitle = "original title"; currentTitle = updateTitle(currentTitle); console.log(currentTitle) I'm just starting to learn JavaScript and I'm curious about why this code behav ...

What is the best way to incorporate a custom string into an Angular application URL without disrupting its regular operation?

In my Angular application with angular ui-router, I am facing an issue with the URL structure. When I access the application from the server, the URL looks like localhost/..../index.html. Once I click on a state, the URL changes to localhost/.../index.htm ...

Tips for eliminating repeated values in a textbox

<script> $("#filter").on("shown.bs.popover",function(){ $(".popover-content input[type=checkbox]").on("click",function(){ if(this.checked) { this.setAttribute("checked","checked"); } else { ...

Ajax is failing to receive the PHP response

I've been struggling with retrieving values from the database using AJAX during the window load event. When I directly access the PHP script, I see the correct values on the screen. However, when trying to fetch these values through AJAX on another pa ...

Best practices for effectively implementing Vuex getters within the Nuxt Vue Composition API

I have been using @nuxtjs/composition-api(0.15.1), but I encountered some issues when trying to access Vuex getters within computed(). Below is the code snippet using composition API: import { computed, useContext, useFetch, reactive } from '@nuxtjs/ ...

"Embedding PHP code within HTML tags, which is then embedded within

Running into an issue within a while loop... echo 'var contentString = '<div id="content" > <div id="bodyContent"> <p>' + $row[name]+ '</p> ...

Scrolling automatically

I'm experimenting with creating a typing effect using JavaScript and the typed.js library, found here: My approach involves using a div as a container. However, I've encountered an issue - when the text reaches the height of the div, scroll bars ...

Retrieving a single property of an object in Vuetify's v-select component

Currently, I am in the process of developing a form using Vuetify. This form includes inputs with preset values sourced from objects. These objects contain two key properties: name and id. In line with Vuetify's documentation, I have utilized the item ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

JavaScript sorted arrays are an efficient way to keep data

In my dataset, I have an array of objects representing various products. Each product object includes a field called ratingReviews and another field called price, which can either be a string or an object. If the price is represented as an object, it conta ...

Having trouble combining different styles with Material-ui and Radium?

Trying to integrate Radium with Material-ui has presented a challenge. Attempting to apply multiple styles to a single Material-ui component results in no styling being applied. For instance, the following code fails to render any styling: <MenuItem st ...

Is there a way to use jQuery to make a div fade in and toggle over another

I have created a test page and I am looking to achieve a specific effect when the page loads. I want everything on the page to be hidden initially. When I click on the "About" text, I want it to fade in using fadeToggle(); however, when I click on "My work ...

Leverage props in Vue 3 composables

While upgrading an app from vue 2 to vue 3, I encountered some difficulties with composables. My issue revolves around using props in the composable, which doesn't seem to work as expected. The code snippet is extracted from a functioning component an ...

The use of an Authorization header is not compatible with HTTP GET requests

I recently incorporated VueSession into my project to handle user sessions. One of the components in my application is a login form that communicates with my backend (Django) to obtain a JWT token. However, I encountered an issue where although the login p ...

Utilize JSON data to display markers on Leaflet maps

I am exploring the world of Leaflet and I have a question about loading markers from a database into a leaflet map using PHP. In my PHP code, I extract latitude and longitude data from the database based on the selected ward and encode it in JSON format. ...

Utilize React without integrating a router component

For my web application built with reactjs, I am considering creating a multi-page site rather than a single page. Should I bundle all the react code into one file and include it on every page of the application, then utilize the exposed function to render ...