Assign specific CSS classes to elements based on the v-model value in Vue.js

Looking to create a dynamic table using Vue and trying to add a class to a row when a checkbox is checked. Each checkbox is associated with a specific value in an object of objects. View the code on Codepen.

<tbody>
      <tr v-for="row in filteredData" 
          :key="row.id" 
          :class="{'is-selected':checkboxes[row.id].checked}">
        <td>
          <input type="checkbox" v-model="checkboxes[row.id].checked"></td>
        <td>{{row.id}}</td>
        <td>{{row.name}}</td>
        <td>{{row.position}}</td>
        <td>{{row.salary}}</td>
      </tr>
    </tbody>

Despite no errors or warnings, the functionality is not working as expected. Any suggestions for resolving this issue would be greatly appreciated.

Answer №1

Here is the issue at hand:

this.checkboxes[data[index].id] = { id: data[index].id, checked: false };

The object property does not become reactive when defined in this manner.

You can read more about reactivity in Vue.js here.

Modern JavaScript limitations mean that Vue cannot automatically detect when properties are added or removed.

Vuex does not permit adding new root-level reactive properties to an existing instance dynamically. However, you can add reactive properties to a nested object using the Vue.set(object, key, value) method

To make the object property reactive, utilize the .$set method.

  createCheckboxArr: function(data) {
    for (let index = 0; index < data.length; index++) {
      this.$set(this.checkboxes, data[index].id, {
        id: data[index].id,
        checked: false
      });
    }
  }

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

Uncomplicating Media Queries in Styled Components with the Power of React.js and Material-UI

My approach to handling media queries in Styled Components involves three distinct functions. One function handles min-width queries, another deals with max-width, and the third caters to both min-width and max-width scenarios. Let me walk you through eac ...

Using JQUERY to handle event bubbling in the DOM after an AJAX call

I have been attempting to dynamically append content to a specific div using .ajax() and then utilize the new content within a jQuery Dialog. I believe that my usage of .on() is correct, but it appears that the DOM is not being properly updated. Here is t ...

Encountering the error message "ws02 script tag does not define Map"

When I try to create a map using the following code: let myMap = new Map(); I encounter the error shown below. Script Error: The script engine encountered an error while executing the inlined Javascript function 'mediate'. com.sun.phobos.script. ...

What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object: let obj = { "sessions": [{ "date": "15-05-2021" }, { "date": "16-05-2021" }, { "date": "18-05-2021" }] } The desired ...

ESLint does not recognize the types from `@vuelidate/core` when importing them

When working with TypeScript, the following import statement is valid: import { Validation, ValidatorFn } from '@vuelidate/core' However, this code triggers an error in ESLint: The message "ValidatorFn not found in '@vuelidate/core' ...

The jQuery click event is failing on the second attempt

My PHP code dynamically generates a list, and I want to be able to delete rows by clicking on them. The code works fine the first time, but not the second time. HTML <li> <div class="pers-left-container"> <img src="<?php ech ...

Unsuccessful attempt at testing RequireJS in a straightforward manner

As a beginner in RequireJS, I am currently experimenting to gain some experience. My goal is to make require load basic Angular first and then manually bring in Angular UI Bootstrap. However, I am encountering an issue where UI Bootstrap complains that ang ...

Adding content in real-time at the current cursor position within a Contenteditable element using Angular

I have a contenteditable div where I am facing an issue with pasting text. Whenever I try to paste some text into the div, it always gets pasted at the end. I am using ViewChild to access the reference of the contenteditable div and utilizing innerText to ...

Updating is not happening with ng-repeat trackBy in the case of one-time binding

In an attempt to reduce the number of watchers in my AngularJS application, I am using both "track by" in ngRepeat and one-time bindings. For instance: Here is an example of my view: <div ng-repeat="item in items track by trackingId(item)"> {{ : ...

Employing setTimeout within a repetitive sequence

function displayColors() { $.each(colors, function(index) { setTimeout(function(){ revealColor(colors[index]); }, 1000); }); } I'm attempting to create a loop where the revealColor function is executed every second until all colors ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Encountering a crash issue with JMeter's Selenium Sampler while attempting to click on a button with the Phantom

After building a JMeter Project, I have been utilizing the WebDriver Sampler (Selenium) to monitor response times during interactions with a particular feature on a webpage. To test my project, I have experimented with both Firefox and Chrome Driver confi ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

HTML Menu with Ajax functionality designed to work seamlessly without relying on JavaScript

I'm working on making my navigation system compatible with both clients who have JavaScript disabled and those who can use Ajax. Currently, I have dynamic links generated inside the navigation like "index.php?page=/cat/page.php". <li id="sidebarit ...

Rails backend is struggling to receive Crossrider ajax post requests with JSON payload

I am encountering an issue where my attempts to post a JSON object to a remote server (Rails) are failing. The POST parameters seem to be converted to a url-encoded string instead of being sent as 'application/json'. Here is an example of what I ...

What steps should I take to make this slider functional?

How can I achieve a sliding effect on this code? I want the div to slide out when the button is clicked, but I also want the button itself to move. Additionally, how can I ensure that the image and text are displayed in two columns? In my IDE, it appears a ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

What steps should I take to solve this wheel-related issue in my Vue 3 application?

I have been developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I am tackling the implementation of a search feature and I've encountered a bug. The "search-box" component is located in src&b ...

Creating Web Components using JavaScript on the fly

I tried to create web components directly from JavaScript, but I encountered an issue where the public constructor could not be found. Here's a basic example to illustrate the situation: The HTML Template: <polymer-element name="wc-foo" construct ...