What is causing the issue with Vue.js :class not functioning properly when it relies on a property of a list

Here is a snippet of my HTML code:

<tr v-for="product in products"
:class="{'bg-red': product.toWrite }" :key="product.name">
  <td @click="setObjectToWrite(product.name)" class="show-hover">
    <u>{{product.name}}</u>
  </td>
</tr>

I have an @onclick handler:

  setObjectToWrite (name) {
    // this.products = []
    let products = this.products
    products.forEach(p => {
      if (p.name == name) {
        p.toWrite = true // ignores
        p.name+=' ' // now displays
      }
    })
    console.log('new products', products) // OK
    this.products = products
  },

Although the handler seems to be working, as I can see the products array being updated in the console. However, the CSS is not changing as expected. (Changing the .name class does result in visible changes).

The initial state of my products array is: [{name: 'some name'},...]

I am somewhat puzzled and feeling like I may have misunderstood something.


After receiving assistance from @Ross Allen, I made some minor adjustments to get it to work:

setObjectToWrite (product) {
    let name = product.name
    let products = [...this.products] 
    products.forEach(p => {
    ...

Answer №1

In the case where toWrite is a new property, Vue will not be able to detect its addition. You can read more about this limitation in Vue's reactivity documentation for objects: Vue reactivity for objects: "Vue cannot detect property addition or deletion".

To work around this issue, I recommend treating values in data as immutable. For scenarios like this, you should create new objects whenever you need to add properties:

  setObjectToWrite (name) {
    const nextProducts = this.products.map(p => {
      if (p.name == name) {
        // By creating a new Object, Vue will detect this change and re-render
        return {
          ...p,
          toWrite: true,
        };
      } else {
        return p;
      }
    })
    this.products = nextProducts
  },

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

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

Exporting SVG to image in Ionic is successful on Android devices, but the image gets cut off when viewed on

I am facing an issue with exporting an SVG as a base64 encoded image and sending it to the server for storage on Google Cloud Storage. The process works fine on Android and in browsers, but fails when attempted on a physical device running IOS. On IOS, t ...

Adjust Mui Autocomplete value selection in real-time

I have implemented Mui AutoComplete as a select option in my Formik Form. <Autocomplete disablePortal options={vendors} getOptionLabel={(option) => option.vendor_company} onChange={(e, value) => {setFieldValue("vendor_id", value. ...

This is some guidance on toggling the visibility of dynamically created divs in Vuejs when a button is clicked

I am working on a project where I have dynamically created buttons and divs. The goal is to show the corresponding div when a button is clicked, while hiding the rest of the divs. Since the number of buttons and divs is not predetermined as they are gene ...

Optimizing load behavior in React using Node.js Express and SQL operations

As someone who is fairly new to programming, I have a question regarding the connection between server and client sides in applications like React and other JavaScript frameworks. Currently, I am working with a MySQL database where I expose a table as an ...

Creating a unique Angular filter involves combining different techniques and functionalities to tailor

Hey there! I'm just diving into the world of Angular JS and I'm looking to filter any Twitter text that comes back containing a hashtag, and turn that word into a clickable link. For example: If the returned twitter text is "The quick brown #f ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

Effortlessly create a seamless transition in background color opacity once the base image has finished

I've set up a div with a sleek black background. Upon page load, I trigger an API request for an image, which is then displayed in a secondary div positioned behind the main one. After this, I aim to smoothly transition the overlaying div's opaci ...

Upon executing the `npm start` command, the application experiences a crash

When I tried following the steps of the Angular quickstart guide, I encountered some errors after running "npm start". Here are the errors displayed: node_modules/@angular/common/src/directives/ng_class.d.ts(46,34): error TS2304: Cannot find name 'Se ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone! I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page: Input their address Completing the form Submit the form Clicking to submit Update the view to display the add ...

Handling Vuex: Attempting to execute a code block within a Getter

I am experiencing an issue with my Vue getter method: getVipCustomersKeys(state) { if (state.vipCustomers) { let arr = []; for (x in state.vipCustomers) { arr.push(x); } } return arr; }, Upon inspecting the ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Merging the functions 'plainToClass' and 'validate' into a single generic function in NodeJs

Here's the issue I'm facing: export const RegisterUser = async (request: Request): Promise<[number, UserResponse | { message: any }]> => { let userRequest = plainToClass(UserRequest, request.body); let errors = await validate(u ...

Do you think it's wise to utilize React.Context for injecting UI components?

I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...

Tips for formatting the return Date when utilizing the setDate() method

I set the end of the week to be the upcoming weekend using the following code snippet this.weekEnd = new Date(this.currentDate.setDate(end)); Now, my goal is to update the weekEnd by adding 7 days to it. I attempted to achieve this as shown below, however ...

React Select only enabling single selection at a time

Currently, I am in the process of updating my react app to version 16.8 and also updating all associated libraries. One issue that has come up is with two drop-down selects from Material UI. Since the update, the multi-select option no longer allows multip ...

Exploring the versatility of combining CSS classes with MUI 5 SX prop

Is there a way to use multiple CSS classes with the MUI 5 SX prop? I've defined a base class for my Box components and now I want to add a second class specifically for styling the text inside the Box. When I try to apply both classes like sx={styles. ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

Discovering the audio file URL hidden within javascript code

Is it possible to programmatically locate a link to an audio pronunciation clip on a website? I am in the process of creating a personalized language learning Anki deck. The specific site I am referring to is: When clicking on "Framburður," the audio cli ...