Is it possible to create a list with dynamic checkboxes in Vuetify that can be clicked on to select them?

I'm currently working on a project that involves creating a list dynamically populated with data from an API. The goal is to have clickable list items that can be selected.

However, I've run into an issue where the checkboxes are functioning correctly, but clicking on the rows themselves does not check them off.

This is the template I am using:

<div id="app">
  <v-app>
    <v-list dark>
      <v-list-tile v-for="(color) in colors" :key="color.hex" @click="">
        <v-list-tile-action>
          <v-checkbox v-model="selected" multiple :value="color" />
        </v-list-tile-action>
        <v-list-tile-content @click="">
          <v-list-tile-title>{{ color.label }}</v-list-tile-title>
        </v-list-tile-content>
      </v-list-tile>
    </v-list>
    <p>Selected items:</p>
    <pre>{{ selected }}</pre>
  </v-app>
</div>

Here is the JavaScript code being used:

new Vue({
  el: "#app",
  data: () => ({
    selected: [],
    colors: [
      { hex: "#f00", label: "Red" },
      { hex: "#0f0", label: "Green" },
      { hex: "#00f", label: "Blue" }
    ]
  })
});

If you'd like to experiment with the code, you can access it on Codepen by following this link: https://codepen.io/anon/pen/vvqeLz

I am looking for suggestions on how to address the challenge of making the list items clickable to properly check the boxes without having to pre-create a fixed variable or modify the structure of the array containing the data. Any innovative ideas are welcome!

Answer №1

Check out my solution below, view the Codepen demo

To achieve this functionality, I implemented a method that alternates between adding and removing colors from an array. Additionally, I enabled the click event for the row itself using

@click.capture.stop="toggleColor(color)"
.

The use of .capture.stop ensures that if a user clicks on a select box, the method will not be triggered again. Therefore, clicking on a select box results in both the select box and the row toggling the value, effectively canceling each other out.

methods: {
  toggleColor (color) {
    if (this.selected.includes(color)) {
      // Remove the color
      this.selected.splice(this.selected.indexOf(color), 1);
    } else {
      // Add the color
      this.selected.push(color);
    }
  }
}

Answer №2

Check out this Codepen example

  computed: {
    selectedColors: function() {
      return this.colors.filter(color => color.selected)
    }
  }

This code snippet generates an Array of all selected colors.

By using this approach, you gain two key advantages. You can set predefined selections before any user interaction occurs, and you have the flexibility to modify these selections independently of the checkbox component itself.

Answer №3

Unique Codepen Link

    handleColorSelection(color) {
      let index = this.selectedColors.indexOf(color);
      if (index === -1) {
        this.selectedColors.push(color);
      }
      else {
        this.selectedColors.splice(index, 1);
      }
    }

@Goodgy, modifying original data directly is not recommended. Using a method would be a better approach.


UPDATE: Check out another solution here

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

"Why does Sequelize migration successfully create a table, yet the models are unable to establish a connection to the

I am currently learning how to use the Sequelize ORM in Node.js and save data in a PostgreSQL database. My primary objective is to insert user data into the Users table. I have successfully created the table using migration; however, I am encountering dif ...

Could anyone assist me in positioning my personalized Context Menu beside my cursor?

If possible, I would appreciate some assistance with my custom context menu. It may require some minor tweaks or a fresh idea on how to address the issue. Ideally, I would like to keep the HTML and CSS somewhat unchanged. [I'm not sure what to write ...

Closing a live search box by tapping away from it

The link I found as the best example for this topic is: http://www.example.com In the example provided, if you enter a keyword in the search field, suggestions will drop down. I have implemented this code but would like to make a slight modification. I w ...

The error message "reload is not defined" indicates that the function reload

Initially, I encountered the error TypeError: require(...) is not a function, prompting me to add a semicolon at the end of require("./handlers/slashcommands"). However, this led to a new issue: ReferenceError: reload is not defined. This occurre ...

Utilizing React to implement a timeout feature for communicating with Firebase

Currently, I am working with React and Firebase, and I need to manage the situation when a call to the database is pending for too long by displaying an error message. Below is my database call: fire.database().ref('user/').once('value&ap ...

The object function router(req, res, next) is encountering an error as it does not contain the required method for handling the request

I am trying to add a new row to my MySQL database, but I encountered an error message. Here is the scenario: I have set up Passport and hjs in my project. I am passing form data from app.js to a JavaScript file where I aim to insert the data. Object funct ...

Bringing in features in Vue.js

Looking to incorporate a utils service into my Vue component: import utilities from './utils'; export default { name: 'grid', props: { 'gridInit': { type: Object, require: true }, 'gridDataInit&a ...

The ES6 Vue and Webpack project functions smoothly on Chrome, yet encounters compatibility issues on IE11

Working on a project using ES6, Vue, and Webpack. The project is successfully running in Chrome, but encountering issues when trying to run it in IE11. An error is being thrown with the following message. Any assistance would be greatly appreciated. https ...

Is it possible to have more than one button for each item on my Shopping List App?

I am developing a shopping list app that allows users to add items to a list. Each item added triggers the display of a button next to it, enabling users to remove the item from the list when needed. However, a problem arises as more items are added – i ...

Make sure that a specific script is loaded prior to another script

I'm struggling to understand how scripts are loaded on a page. I have jQuery plugins that rely on other scripts. Specifically, I am using the timeago jQuery plugin. I have loaded these scripts in the head in the following order: <script src="< ...

Executing python code from a JavaScript (Node.js) program without the need to create a child process

I have a unique setup where my hardware is running on nodejs, while my machine learning code is written in python3. My goal is to invoke the python3 program from nodejs (javascript) and pass data as arguments to the Python script. While researching, I cam ...

What is the best way to access the current webdriver instance using code?

Currently, I am in the process of creating an end-to-end test suite with Protractor. As Protractor is based on WebdriverJS, I am attempting to utilize some of its functionality. More specifically, my goal is to incorporate certain behaviors using Webdriv ...

The click event does not point to the servlet (IDEA, java)

I am facing an issue where the command $.get('MyController1', function (responseText) is not sending to my servlet. I am using ajax and after clicking the button it should send to my servlet ('MyController1' or 'MyController2' ...

Ways to modify the prop of useSlot() in Vue 3

I have a query about how to access the props change retrieved from useSlots() This is a file that defines the Parent component with the Child component as the Parent component's slot. I have also passed some props to the Child component. <script s ...

Guide on debugging Express.js server code on Node with Visual Studio Code by Attaching to a live process

Here is a list of the tools I have: Latest Visual Studio Code Express js Node js Take a look at my Attach configuration below: { "version": "0.1.0", // List of configurations. Add new configurations or edit existing ones. "configurations": ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

Guide to running a Vue 3/Vite application in library mode for testing or demonstration needs

Currently, I am in the process of developing a Vue 3 components library and transforming it into an npm package using Vite.js. Following the guidelines provided in the official documentation, I have successfully configured Vite. However, I am faced with th ...

Is there a way to trigger the activation of the datepicker during the `onLoad` event?

For my project, I am utilizing this datepicker. While I am familiar with using scripts to handle changes in the date value, I am unsure of how to implement it on page load. $('.date_set .date').datepicker({ startView : 0, ...

Employing JavaScript to set a variable that changes dynamically

In my code, I have a functionality that allows for changing different dropdowns with similar ending IDs. In other parts of the code, I have assigned variables rl and rl_extra as well as rs and rs_extra. Now, when the var prefix is determined to be either ...

Tips for concealing code on the client side in vue/nuxt through Server Side Rendering techniques

I need to execute server-side processing without exposing it to the client side. Although I have successfully used either fetch or asyncData for state population, I want to keep the process hidden from the browser. Here's an example: <template> ...