Choose default checkboxes within a Vuetify list item group based on an array of objects

I'm having trouble preselecting checkboxes within a v-list-item-group. I can't seem to figure out what the true-value should be set to in order for the checkbox to be checked.

I've also attempted changing the value of true-value to column.value, but that didn't work either.

Unlike most examples I've come across, the model for this v-list-item-group consists of an array of objects instead of primitives like usual.

In the provided code snippet example (unfortunately, couldn't get it to run in the sandbox), "Column 2" is supposed to be preselected.

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    defaultColumns: [{
        value: 'column1',
        text: 'Column 1',
      },
      {
        value: 'column2',
        text: 'Column 2',
      },
      {
        value: 'column3',
        text: 'Column 3'
      },
    ],
    selectedColumns: [{
      value: 'column2',
      text: 'Column 2',
    }],
  }),
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/2.2.13/vuetify.js"></script>
<div id="app">
  <v-app>
    <v-list>
      <v-subheader>
        Select columns
      </v-subheader>

      <v-list-item-group v-model="selectedColumns" multiple>
        <v-list-item v-for="column in defaultColumns" :key="column.value" :value="column">
          <template v-slot:default="{ active, toggle }">
            <v-list-item-action>
              <v-checkbox
                :input-value="active"
                :true-value="column"
                color="primary"
                @click="toggle"
              />
            </v-list-item-action>

            <v-list-item-title>
              {{ column.text }}
            </v-list-item-title>
          </template>
        </v-list-item>
      </v-list-item-group>
    </v-list>
  </v-app>
</div>

Answer №1

Implement v-model with v-checkbox instead of using toggle or click events. Simply assign a boolean value to v-model and the checkbox will automatically select/unselect based on this value, as explained in the Vuetify documentation:

<v-checkbox
      v-model="checkbox"
      :label="`Checkbox 1: ${checkbox.toString()}`"
    ></v-checkbox>
.
..
...
<script>
  export default {
    data () {
      return {
        checkbox: true,
        radioGroup: 1,
        switch1: true,
      }
    },
  }
</script>

To demonstrate a possible solution, I have provided an example:

https://codepen.io/emkeythekeyem/pen/XWbjzav

HTML :

<div id="app">
  <v-app>
    <v-list>
      <v-subheader>
        Select columns
      </v-subheader>

      <v-list-item-group v-model="selectedColumns" multiple>
        <v-list-item v-for="column in defaultColumns" :key="column.value" :value="column">
          <template v-slot:default="{ active, toggle }">
            <v-list-item-action>
              <v-checkbox
                :input-value="active"
                color="primary"
                v-model="selectedColumns.filter(e => e.value === column.value).length > 0"
              />
            </v-list-item-action>

            <v-list-item-title>
              {{ column.text }}
            </v-list-item-title>
          </template>
        </v-list-item>
      </v-list-item-group>
    </v-list>
  </v-app>
</div>

Vue

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    defaultColumns: [{
        value: 'column1',
        text: 'Column 1',
      },
      {
        value: 'column2',
        text: 'Column 2',
      },
      {
        value: 'column3',
        text: 'Column 3'
      },
    ],
    selectedColumns: [{
      value: 'column2',
      text: 'Column 2',
    }],
  }),
})

Answer №2

After some trial and error, I found a solution by converting an object to strings when retrieving a value and reconstructing the object when assigning a value based on the default comparisons.

To provide clarity, here is a simplified example since the actual code is confidential:

selectedColumns: {
  get() {
    return this.selectedColumns.map(
      (column) => column.value
    )
  },

  set(value) {
    const columns = this.defaultColumns.filter(
      (column) => value.includes(column.value)
    )

    // Perform operations with `columns`, such as storing them in a repository.
  }
}

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 could be causing my node-statsd client script to not terminate?

When attempting to log a metric to a StatsD server using the node-statsd library, I encountered an issue where the script did not exit automatically. The code snippet in question is as follows: var StatsD = require('node-statsd').StatsD; var cli ...

The functionality of Bootstrap Tabs is compromised when used within a jQuery-UI dialog window

My goal is to develop a user interface similar to MDI for my application. To achieve this, I am utilizing the dialog feature of the jQuery UI library. To dynamically create a dialog window on demand, I have coded a helper function as shown below: functio ...

Enhance your browsing experience by inputting valuable information into the

I am looking to enhance a text box by adding values. The text box already has a default value of 10, and I want to create a button that will add new text boxes with a limit of 4. My goal is to continuously add values from text box 1 to text box 4. For exa ...

Can you explain how to create a function in Angular that accepts a number as an argument and then returns the square of that number?

I am working with an array of numbers and I want to show each number in the list along with its square value. To do this, I need to create a function that takes a number as input and returns its square as output. Here is what I have attempted so far: co ...

"How can I update a table in Flask using Chart.js and Pandas

I have developed a basic Flask application that includes a bar chart using Chart.js and a data table displayed below it. Check out the setup below: https://i.sstatic.net/QB6jQ.png (Live view: ) The bar chart I created counts the number of items for each ...

Encountered an ERROR with MONGO_OBJECT_REMOVED while attempting to Add Data to Mongo Collection

While attempting to insert data into MongoDB, the console.log output for rcitems showed an error message indicating "MONGO_OBJECT_REMOVED". I am currently utilizing Meteor, Blaze, Simple-Schema, and Collection2. The expected outcome for rcitems is to dis ...

What causes a horizontal line to form when a user enters white space?

I have written a piece of code which seems to be causing an issue when running it. Whenever I input empty spaces, it results in creating a horizontal line. import React, { Component } from 'react'; export default class App extends Component { co ...

Loop through an array of div IDs and update their CSS styles individually

How can I iterate through an array of Div IDs and change their CSS (background color) one after the other instead of all at once? I have tried looping through the array, but the CSS is applied simultaneously to all the divs. Any tips on how to delay the ...

Troubleshooting issue with TypeScript: Union types not functioning correctly when mapping object values

When it comes to mapping object values with all primitive types, the process is quite straightforward: type ObjectOf<T> = { [k: string]: T }; type MapObj<Obj extends ObjectOf<any>> = { [K in keyof Obj]: Obj[K] extends string ? Obj[K] : ...

The integration of AngularJS with Bootstrap 3 accordion seems to encounter issues when included through ng-view

Here's the issue: When using the accordion in a view loaded with the ng-view directive, the accordion title clicks stop working correctly. Check out this demo for an example However, when the accordion is used directly on the page without ng-view, i ...

jQuery encountering an issue with parsing JSON data (error message displayed)

Upon reviewing similar questions, it seems that most issues arise from either invalid JSON or incorrect headers on the XMLHttpRequest. My case, however, does not seem to fall into either of those categories. I have a reliable JSON server at my disposal. Y ...

Utilizing AngularJS and RequireJS to incorporate a controller into the view

I am facing an issue while trying to add an Angular controller to my HTML view. Typically, in Angular, this can be done using: ng-controller="<controller>". However, due to my use of RequireJS, I have had to implement it differently. I need to includ ...

What is the process for altering the color of an HTML output depending on its values?

I created a simple HTML code to showcase some outcomes. The possible results are SUCCESS, Failure, and Still Failing. I want these results to be displayed with corresponding colors, such as green for SUCCESS, and red for both Failure and Still Failing. I ...

Potential issue of excessive memory usage in node.js when running an Express server with PM2

Currently, I am focusing on a specific aspect of a suite of services designed to work in conjunction with an app/platform. The particular area that requires assistance is related to a vanilla express server used to provide our client app (a react app). We ...

What's the best way to create an onclick event for a li element that includes a pseudo-element ::before

I have successfully created a Timeline using HTML and CSS elements. The visual result is as follows: My goal is to enable users to click on the second circle, triggering a color change in the line that connects the first and second circles. This color tra ...

Instantiating objects directly from factories in AngularJS

How can I make a direct call to RESTService.get without using AngularJS’ dependency injection in the code snippet below? angular.module('RESTModule', ['ngResource']). factory('RESTService', ['$resource', functio ...

Tips for sending form data as JSON to a servlet with AJAX:

I am struggling to send login information in JSON format to a servlet using AJAX. The issue I'm facing is that the servlet is receiving null values. Interestingly, my servlet functions properly when I transmit the data without utilizing AJAX. However, ...

conducting a validation using ajax when submitting

Currently, I am exploring the implementation of AJAX validation within a submit() handler for a web form. The AJAX functionality is executed using $.ajax() from jQuery. While setting async: false yields successful results, it triggers a deprecation notice, ...

Exploring the use of v-model in Vue3 child components

After some exploration, I recently discovered that in Vue3, the v-model functionality does not work responsively or reactively with child Component. The following code snippet showcases how the username data gets updated: <template> <div> ...

Error: The system is unable to destructure the 'username' property from 'req.body' since it is not defined

Encountering a persistent issue with an error that I've been trying to resolve for days without success. The problem arises when attempting to register a user in the project, resulting in error messages being displayed. Here's a snippet of the co ...