Vue.js - The table updates successfully, however, the data for the selected checkboxes remains unchanged

Encountered a persistent bug that is giving me some trouble. I have a table with rows that can be selected, and when a checkbox is checked, the total amount in the column should be calculated.

However, whenever there is a change in the table data through the datepicker, the merchant total on the right side and the amount in the selected checkboxes object fail to update and reflect the current table state.

Displayed below are two images to illustrate this issue.

Check out the codepen for reference: https://codepen.io/anon/pen/NmKBjm

I managed to find a solution, but I suspect there might be a more efficient method using v-model which I'm struggling to implement. The approach involves fetching the data and then updating the selected object with that data.

this.volume = response.data;

this.total = this.volume.reduce(function(p, n) {
    return p + parseFloat(n.amount);
}, 0);

let merchants = this.selected.map(m => m.merchantName);
let filterMerchants = this.volume.filter(e => e ? merchants.includes(e.merchantName) : null);

this.selected = filterMerchants;
this.onCheckboxChange();

https://i.sstatic.net/7rAvG.png

https://i.sstatic.net/1GK9g.png

Here is the snippet of my code.

<v-data-table v-model="selected" id="transactions-volume-table" :headers="tableHeaders" :items="volume" item-key="merchantName" :loading="loading" :search="searchTable" hide-actions class="elevation-1">
<v-progress-linear slot="progress" color="blue" indeterminate></v-progress-linear>
<template v-slot:items="props">
    <td><v-checkbox v-model="props.selected" @change="onCheckboxChange" primary hide-details></v-checkbox></td>
    <td class="text-xs-left">{{ props.item.divisionName }}</td>
    <td class="text-xs-left">{{ props.item.merchantName }}</td>
    <td class="text-xs-left">£{{ props.item.amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") }}</td>
</template>
</v-data-table>

data() {
  return {
      search: {
          fromDate: new Date().toISOString().substr(0, 10),
          toDate: new Date().toISOString().substr(0, 10)
      },
      fromDateModal: false,
      toDateModal: false,
      searchTable: '',
      loading: true,
      volume: [],
      total: null,
      merchantTotal: 0,
      tableHeaders: [{ text: 'Select', sortable: false },
                     { text: 'Division', value: 'divisionName', sortable: true },
                     { text: 'Merchant', value: 'merchantName', sortable: true },
                     { text: 'Amount (£)', value: 'amount', sortable: true }],
      selected: []
  }
}

onCheckboxChange() {
    console.log(this.selected);
    this.merchantTotal = this.selected.reduce(function(p, n) {
        return p + parseFloat(n.amount);
    }, 0);
}

Answer №1

Ensure to update the total for the merchant only when there is a change in the checkbox. Also, remember to update the merchant total if there are changes in your dates. The date change does not automatically trigger a change in the checkbox event.

UPDATE
No, the checkbox change event is only activated when there is an actual change (clicking on it or manually triggering it). Since your merchantTotal is not a computed property, it is not reacting to any changes. Consider making it computed, as you are essentially trying to replicate a computed action.

UPDATE
Please refer to this example I have created. Similar to your scenario, everything revolves around the selected rows. When the selected variable changes (due to applied filters or toggling checkboxes), the total will be recomputed. Although I used products instead of merchants in my example, the concept remains the same.

UPDATE
Have you considered adding a unique identifier for each merchant in the dataset? Alternatively, you can create an ID based on two rows (division and merchantname). This approach will allow you to calculate data using the volume corresponding to the selected merchant ID or unique identifier, as demonstrated. Another method would involve deselecting merchants when data changes, though this may not be very user-friendly.

Initially, I assumed the issue was related to Vue implementation, but now I believe it may stem from how the Vuetify datatable operates in your case.

Answer №2

Apologies for the confusion, let me clarify.

In Vue, there is a limitation in reactivity when it comes to detecting changes in objects. This means you won't be able to observe when your volume array changes due to datepicker modifications. To address this issue, you should utilize this.$set to monitor changes in objects (remember, an array is also considered an object).

For more information, check out: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

Below is an example code snippet:

<div id="app">
    {{ message[0] }}
    <button v-on:click="change">Change</button>
</div>


<script>
    var app = new Vue({
        el: '#app',
        data: {
            message: [45,35,50]
        },
        methods: {
            change: function () {
                //this.$set(this.message, 0, 35);                    
                message[0] = 35;
                console.log(this.message);
            }
        }
    });
</script>

Uncomment the line that's been commented out and give it a try to see the difference.

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

Interfacing Contact Form Data from Vue Application to Magento Using API - A Step-by-Step Guide

Introduction A custom vue-component has been implemented on the application, serving as a contact form. This component is imported into the header component and enclosed within a modal container. The primary function of this contact form is to trigger an ...

Using Vue.js to group JSON arrays multiple times

I have a program that I utilize to import a CSV data file and then convert it into JSON format. The resulting JSON structure is as follows: { "Class": "Cultivated Mushrooms", "Type": "Shii-take", "Grade": "Medium", "LvH": "SP", "Description": " ...

Using global variables in NodeJS MySQL is not supported

Why am I unable to access the upcoming_matches array inside the MySQL query callback? Whenever I try to log upcoming_matches[1], I get a 'TypeError: Cannot read property '1' of null' error message in the console. This indicates that th ...

monitor the location of a div within a textarea

My question revolves around a textarea that is linked to a draggable div through the following code: $('#content').children().draggable({ drag : function () { $('#textarea').text("left:" +($(this).position( ...

What is the best way to eliminate the content of an element using javascript/typescript?

The progress bar I'm working with looks like this: <progress class="progress is-small" value="20" max="100">20%</progress> My goal is to use javascript to remove value="20", resulting in: <progre ...

Fixing the version mismatch error when attempting to create a Vue project

While attempting to create a vue project using vue create shop, I keep encountering the following error message: Error: Vue packages version mismatch: - <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5838090b5c7dbc3dbc4c4" ...

Error! There seems to be a missing start script for Vue.js in the npm ERR

After trying to install Vuetable with the command npm install vuetable-2@next --save, I encountered the following error message: npm ERR! missing script: start npm ERR! A complete log of this run can be found in: npm ERR! x\AppData\Roaming& ...

Attempting to save data to an external JSON file by utilizing fs and express libraries

I've encountered a challenge while attempting to serialize an object into JSON. Despite my best efforts, I keep encountering an error that has proven to be quite stubborn... Below is the code snippet that's causing the issue: APP.post('/api ...

Neglecting the Outcome of Async/Await

I am facing an issue where I need to send different SMS messages to different recipients synchronously, but my current implementation using async/await is not producing the expected results. Below is the code snippet causing the problem: Upon querying fo ...

What happens to the parent scope in Javascript when declaring a subclass and why does it get overridden?

I have two classes in JavaScript, with one inheriting from the other. The structure is as follows: var Parent = (function(){ var self; var parent = function(){ self = this; self.type = 'Parent'; }; parent.protot ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...

Issue opening react modal dialogue box

I'm encountering an issue while trying to implement the headless ui modal. I'm attempting to trigger the modal.js script from my home.js file. In my home.js file, I have the following code snippet: function Home() { const [isOpen, setIsOpen] = ...

Angular js encountered an unexpected error: [$injector:modulerr] ngRoute

https://i.sstatic.net/PATMA.png In my Angular code, I encountered the error "angular is not defined". This code was written to test the routing concept in AngularJS. var app=angular.module('myApp',['ngRoute']) .config(function ($routeP ...

Discover the best places to master AJAX

Although I have come across some related questions here, none of them exactly match mine. I am aware of excellent resources like code-school and code-academy where you can improve your PHP and JS skills by coding directly on the website. However, I am wo ...

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

After incorporating some movement effects into my menu, suddenly none of the buttons were responding

While working on my website and trying to add a close menu button, I encountered an issue where all the menu buttons stopped functioning. Here is the HTML code snippet: <div id="openMenuButton"> <span style= "font-size:30px;cu ...

execute the function whenever the variable undergoes a change

<script> function updateVariable(value){ document.getElementById("demo").innerHTML=value; } </script> Script to update variable on click <?php $numbers=array(0,1,2,3,4,5); $count=sizeof($numbers); echo'<div class="navbox"> ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

Displaying [object Object] in Angular Material datatable

I am currently working on implementing a datatable component using Express and Firebase DB. Below is the service request data: getText() { return this.http.get<nomchamp[]>(this.url) .map(res => { console.log(res); return res }); ...

What is the best way to protect old documents when selecting new files in a multi-file uploader?

I created a file upload feature with file previews using HTML5 and the file reader, which is functioning well. However, I'm facing an issue where old files selected by the user get removed from the input file field if a new file is selected in a singl ...