Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vuetify, how can I make a dynamically list with checkboxes clickable to select them?

I'm trying to create a dynamically generated list (with data from an API), then make the list items clickable to select these items.

The problem is that in this version, the checkboxes work properly, however the rows cannot be clicked to check them.

Template:

<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>

JavaScript:

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

Codepen to play around with it: https://codepen.io/anon/pen/vvqeLz

Compared to the given example, there's no fixed variable I can pre-create to mark a checkbox as selected, and I need the data in one array (as is correctly happening now) to process this later on. Note that the example is simplified to the bare-bone minimum. (excluding props and so forth)

Does anyone have a genius idea on how to make the list items clickable to check the boxes properly?

like image 334
ZeroThe2nd Avatar asked Jan 01 '23 10:01

ZeroThe2nd


1 Answers

Here is my attempt at it, see the Codepen example

What I did was create a method which toggles the adding and removing of a color in the array. Then I added the click functionality for the row itself with @click.capture.stop="toggleColor(color)".

The .capture.stop part checks whether a user clicked on a select box first, and if so it stops the method from firing again. Else once you click a select box both the select box and the row toggle the value, thus cancelling each other out

methods: {
  toggleColor (color) {
    if (this.selected.includes(color)) {
      // Removing the color
      this.selected.splice(this.selected.indexOf(color), 1);
    } else {
      // Adding the color
      this.selected.push(color);
    }
  }
}
like image 128
T. Dirks Avatar answered Jan 05 '23 15:01

T. Dirks