How can I ensure that all items are automatically selected in the v-data-table component?

I am struggling with getting all rows in a v-data-table component to be checked by default when using the checkboxes created by the select-all feature to filter information in the parent component.

So far, I have tried:

  • Setting selectedItems to
    Array.from(this.$store.state.tableItems)
    in the parent component's data (which didn't work due to the item in the store not being defined at that point).
  • Setting selectedItems to Array.from(this.tableItems) in the child component's mounted or created event (which resulted in an "avoid mutating a prop directly" error).

I have a feeling that using a computed property might be the solution to this issue.

(There is probably a more Vue-like way to solve this with actions or events, but as a newcomer to Vue, I am still exploring different approaches.)

MyComponent.vue

<template>
  <v-data-table
    :value="selectedItems"
    @input="$emit('update:selectedItems', $event)"
    :headers="headers"
    :items="tableItems"
    item-key="id"
    select-all
  >
    <template slot="items" slot-scope="props">
      <td>
        <v-checkbox v-model="props.selected" hide-details></v-checkbox>
      </td>
      <td>{{ props.item.id }}</td>
    </template>
  </v-data-table>
</template>
<script>
export default {
  props: {
    tableItems: { type: Array, },
    selectedItems: { type: Array, },
  },
  data() {
    return {
      headers: [
        { text: 'ID', value: 'id', },
      ],
    };
  },
};
</script>

Parent.vue

<template>
  <MyComponent :tableItems="tableItems" :selectedItems.sync="selectedItems"/>
</template>
<script>
export default {
  components: {
    MyComponent,
  },
  data() {
    return {
      selectedItems: [],
    };
  },
  computed: {
    tableItems() {
      return this.$store.state.tableItems;  // set by an axios request in beforeCreate in App.vue
    },
  }
};
</script>

Answer №1

It seems like the solution provided worked for me, as I was already utilizing Vuex. However, I am open to any alternative approaches that might be more satisfying.

store.js

In this file, I am keeping track of the selected items. The initial value is set to null so that when I update the table items after the first axios call, I can assign a default value.

export default new Vuex.Store({
  state: {
    tableItems: {},
    selectedItems: null,
  },
  mutations: {
    setTableItems(state, payload) {
      state.tableItems = payload;
      if (state.selectedItems == null) state.selectedItems = payload;
    },
    setSelectedItems(state, payload) {
      state.selectedItems = payload;
    },
  }
});

MyComponent.vue

In this component, I have made changes to use the selected items from the Vuex store as the value for the data table. I am also committing a mutation for every input.

<template>
  <v-data-table
    :value="selectedItems"
    @input="updateSelectedItems"
    :headers="headers"
    :items="tableItems"
    item-key="id"
    select-all
  >
    <template slot="items" slot-scope="props">
      <td>
        <v-checkbox v-model="props.selected" hide-details></v-checkbox>
      </td>
      <td>{{ props.item.id }}</td>
    </template>
  </v-data-table>
</template>
<script>
export default {
  props: {
    tableItems: { type: Array, },
  },
  data() {
    return {
      headers: [
        { text: 'ID', value: 'id', },
      ],
    };
  },
  methods: {
    updateSelectedItems(event) {
      this.$store.commit("setSelectedItems", event);
    },
  },
  computed: {
    selectedItems() { return this.$store.state.selectedItems; },
  }
};
</script>

Parent.vue

In this component, I simplified the process by directly referencing the store without too much data binding.

<template>
  <MyComponent :tableItems="tableItems"/>
</template>
<script>
export default {
  components: {
    MyComponent,
  },
  computed: {
    tableItems() { return this.$store.state.tableItems; },
    selectedItems() { return this.$store.state.selectedItems; },
  }
};
</script>

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

The issue of Angular curly braces malfunctioning in some simple code examples reversed my

<head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"> </script> </head> <body style="padding: 20px 20pc;"> <div ng-app="app"> ...

The Codeigniter ajax call fails to function properly when an external JavaScript file is incorporated

Why does my Codeigniter ajax request work when JS is embedded internally, but not when I try to use it as an external JS file? View the code for the sample_ajax below: <html> <head> <title></title> <scrip ...

JS/Electron Insert items individually

Apologies if my explanation is unclear. I have a function (shown below) that parses a JSON file and creates a grid of 1550 items. How can I add them one by one instead of all at once? Loading all 1500 items together is taking too long. function addItem () ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...

Creating JSON data that is completely valid using client-side JavaScript

I've been working on creating a JSON explorer/editor. Successfully managed to parse the initial JSON into the div and customize the formatting. Here's the function I utilize to loop through the initial JSON: _iterate(_tab, raw_json){ var tab ...

Watching a live video stream in real-time using WebRTC with React

Here is the HTML code <video ref={videos} autoPlay ></video> <Button onClick={() => navigator.mediaDevices.getUserMedia({audio: true, video: true}).then((mediaStream) => { videos.srcObject = mediaStream; videos.onloadedmetad ...

When the browser's inner width is less than the inner height, use jQuery or JavaScript to show a message on the webpage

I've been having trouble getting this to work and I've attempted various solutions suggested by different sources such as: Display live width and height values on changing window resize php echo statement if screen is a certain size And more, b ...

Node.js Express: Breaking Down Your Application into Modules

Currently, I am working on an express app and have the following code setup: MainApp.js const express = require('express'); const routes = require('./routes') const mainApp = express(); mainApp.listen(3000, () => { console.l ...

Unlimited Lunch Options and Navigational Links

Looking for help with displaying the ul for MAINTENANCE and referencing specified classes from a CSS style sheet that are working elsewhere. However, the sub menu for MAINTENANCE is not showing up. Any suggestions? /* * Superfish v1.4.8 - jQuery menu w ...

Enhancing Element Generation and Data Association through jQuery

Currently, I am seeking a more streamlined approach to generate DOM alterations and update the object within .data(). At the moment, data is being supplied in an array of objects. I construct strings piecemeal, appending them to the table body, and affixi ...

Retrieve the Query String Information from a Link and Generate a New Link in Another List

I am looking to extract information from a link in #list and then use that information to create a new link in #list3. The link I have is http://jsfiddle.net/4y5V6/24/. Is there a way to set it up so that when a link is clicked, it automatically gets added ...

The issue with angular JavaScript in the child component is causing the left side navigation dropdown to malfunction

I'm currently facing an issue with the left side navigation in my home component. The dropdown functionality is not working within one of the routing modules (admin-routing.module.ts). Interestingly, the navigation works perfectly fine in app-routing. ...

Using track by in ng-repeat function triggers an endless $digest-loop issue

It appears that I am still struggling to grasp the mechanism behind ng-repeat, $$hashKeys, and track by. Currently, in my project, I am working with AngularJS 1.6. The Issue: I have an array of complex objects that I want to display as a list in my view ...

Error sending an email through the EmailJS backend JavaScript file

I am in the process of creating a route for my backend JavaScript Express server called server.js that will trigger an email to be sent to my Gmail account using EmailJS. When I attempt to use the following code: const SMTPClient = require("emailjs& ...

Identify whether the Vue model change was initiated by user input or programmatically

I am facing an issue with Vue's reactivity when using a custom component in Quasar 2. Let me explain the scenario: The custom component includes two radio buttons and a select dropdown. Whenever the user changes one of the radio selections, the selec ...

How can I incorporate multiple states into a conditional statement in ReactJS?

Is there a more efficient way to achieve this task? I'm struggling to come up with a cleaner solution as the current approach looks messy. I need to check multiple states in an if statement and the only method I can think of right now is the one prese ...

Showing the values of selected checkboxes in a select dropdown - here's how!

Link to the jsfiddle : https://jsfiddle.net/a1gsgh11/9/ The JavaScript code seems to not be working on the js fiddle platform. My main concern is that I would like the selected checkbox values to display immediately without needing to submit any buttons. ...

Adding a PHP file into an HTML page using JavaScript include

Recently, I was assigned to collaborate with a third-party vendor who displays movie times on their platform. We were given the opportunity to co-brand our website on their platform by creating a wrapper for our site. This wrapper would allow the movie tim ...

Turn off the ability to click on images, but allow users to access the right

https://i.stack.imgur.com/jriaP.png Example image sourced from reddit.com Illustration represents the desired effect using CSS and possibly JS. In essence: I aim to make an image on a website unclickable to its imageURL There should be a context menu ...

Encountering a hiccup during the installation process of Angular CLI

I'm encountering an issue in the command line, seeking assistance C:\Users\admin>npm -v 6.9.0 C:\Users\admin>npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing near '...vkit/core":"8.0.4", ...