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

What is the process for configuring aliases in vuepress or vuejs using configureWebpack?

In my config.js file, I have set the configureWebpack parameter like this: configureWebpack: { resolve: { alias: { 'alias': '/easym/imgs/' } } }, Here is my folder structure: -/easym --/.vuepress -- ...

Encountering obstacles with asynchronous requests while attempting to retrieve an Excel file using ajax

I am coding JavaScript for a SharePoint project, focusing on creating a function to retrieve data from an Excel document in a library. While I have successfully implemented the basic functionality, I am facing an issue with large file sizes causing the dat ...

How Angular JS alters scope when used in a function

I am currently working on a controller that manages the clicks of buttons in a navigation bar. I am trying to find a way to update the value of '$scope.active' with each click event. Below is my previous code which is functional, where the values ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

Unable to send JSON response when making a POST request in Spring MVC controller

When handling a POST request, I have no issues sending a list of objects in response and receiving it in the VueJs client. @RequestMapping(value={"/data/parts"}, method = RequestMethod.POST) @ResponseBody public List<Part> getPartsList( @RequestBody ...

Service Worker error - Received redirected response when RedirectMode is not set to "follow"

Browser: Firefox 58.0.2 (64-bit) I am attempting to create a very basic service worker to store content for offline viewing, following the guidelines provided here and here. After installing the service worker successfully upon loading the page for the f ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...

How come submitting a form without refreshing does not update the database with new values?

I'm encountering an issue with my form and script that is supposed to connect to the operation.php class. Despite having everything set up correctly, the data is not being added to the database and the page does not refresh. I'm perplexed as to ...

Can a function be passed as props in a scenario where both a Parent and Child component are functional components?

I have a component called ParentComponent where I am trying to pass a function named toggleDrawer to another component called ChildComponent in the following way: const ParentComponent = () { const [drawerState, setDrawerState] = useState(false); ...

Having issues with the Axios request interceptor in my Vue application

I am facing an issue with getting axios to work with a request interceptor. The problem is that the interceptor does not seem to be triggered before the request is made. Can someone help me figure out what could be causing this? I have done my research on ...

Guide on linking draggable elements

Currently, I have a set of div elements that I am able to clone and drag and drop into a specific area. Now, I am looking for a way to connect these divs with lines so that when I move the divs, the lines will also move accordingly. It's similar to cr ...

AppleScript: Check if the value of document.getElementById is empty, then fill in the value

Hello everyone, it's my first time asking a question here. I have an AppleScript that takes values from a Numbers document and fills them into different fields of a webform using document.getElementById. Everything is working perfectly so far, but now ...

Tips for managing the most recent keyup event in a search feature

I have a search input on my website. Whenever a user types a letter in it, an ajax request is made to display some content as the result. My goal is to only create an ajax request for the last keyup event when the user types quickly. I came across a soluti ...

Transform your data visualization with Highcharts enhanced with the stylish appearance of DHTML

I am currently using a dhtmlx menu with my charts, specifically the legendItemClick event. It worked perfectly when I was using highcharts 3.0.1. However, after upgrading to version 4.1.7, the function legendMenu_<?=$id?>.showContextMenu(x,y) in the ...

Click to stay in the background

I am currently facing an issue where opening a new tab on click redirects the focus to the child window instead of staying in the current window. I would like the popup to open without blocking and allowing me to maintain focus on my current window. The c ...

Enhancing JSON data in Datatables with additional text

I'm currently looking for a way to insert some text into my data before generating a table using jQuery DataTables. As an example, if my JSON data looks like [1,5,6,12], I would like it to be displayed as [1 seconds, 5 seconds, 6 seconds, 12 seconds] ...

Leveraging the power of AJAX and JSON to showcase dynamic HTML content pulled from PHP

I'm working on retrieving data from my PHP file, and it contains information in the columns Email, FirstName, LastName, and State. $query = 'SELECT * FROM users WHERE LOWER(Email) = :email'; $stmt = $dbh->prepare($query); $stmt->bindV ...

transferring information from PHP to JavaScript through the use of JSON encoding

I am currently in the process of developing a Google maps page that utilizes latitude and longitude data coordinates to generate a heat map displaying the distribution of foxes within a specific area. At present, my application functions properly when the ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

What is the process for including a field specific to a date in a form?

I need the user to select a month and year. In one column, there will be the days of the month they selected [e.g. 1-30]. Users can then add habits in other columns. I want users to be able to input an 'X' for each habit row on a specific date [e ...