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

Extracting keys and values from a JSON string for analysis

My current code for the service now rest outbound call is functioning correctly. However, I am facing issues while trying to parse the JSON body in the second REST call and fetch values in the desired table format. try { var r = new sn_ws.RESTMessageV2 ...

What's the best way to set up server-side pagination for mui-datatable?

Is server-side pagination for mui-datatable implementation a complex task? Challenges: I am facing difficulties in capturing the user-selected value from the rowsPerPage options. When a user selects '15', how can I update these values within ...

Tips for Utilizing Both getElementByID and getElementByTagName Functions in JavaScript

Hi! I'm a beginner in JavaScript and I've managed to retrieve some data using getElementById. Now, I want to extract a specific part using getElementsByTagName. document.getElementById('titleUserReviewsTeaser').innerHTML; " < ...

Having trouble compiling the Electron App because of a parser error

Struggling to set up a basic electron app using Vue 3 and Typescript. Following the successful execution of certain commands: vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve Encountering issues when trying to i ...

What is the method for writing to an HTML file with the use of expressjs?

Alright, I have an interesting idea here. I am looking for a way to allow users to push a button and have a new p element permanently added to the HTML file. This means that even after reloading the page, everyone should be able to see this new element. An ...

Preventing Internet Explorer from automatically scrolling to the top of the page when a new HTML element is dynamically inserted using

On my webpage, I have an ASP:Grid with a small copy button in each row to copy the text inside that cell. The javascript function I created for copying the text is as follows: var copyText = function (textToCopy) { $(".copy").append("<textarea id=&ap ...

Fetching Date and Time from the Internet using PHP

While I understand that similar questions have been asked numerous times before, I have yet to find a solution that fits my specific needs. My question is regarding how to retrieve the current date and time from the internet rather than relying on the loc ...

Is it possible to add a click event to a table row that contains an input checkbox, without interfering with the ability to click the checkbox itself?

I have a table: <table> <tr> <td>Something</td> <td>Something Else</td> <td><input type='checkbox' value='clickme' id='yes'></td> </tr> When a user ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

Hey there, I'm currently working on a PUT request using axios and vue.js to a backend ASP.NET Core controller, but I'm running into an issue

I am trying to send a PUT request to update a product using vue.js, but I am encountering an issue where it passes null to my controller action method. Below is the vue.js code snippet responsible for updating the product: updateProduct() { this.load ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

Accordion nested within another accordion

I am facing a challenge while trying to nest an accordion within another accordion. The issue is that the nested accordion only expands as much as the first accordion, requiring additional space to display its content properly. Any assistance with resolvin ...

divide a single item into several items depending on its attribute

data = {1-inputWidth : '30px' , 1-inputHeight: '30px', 1-color : 'red', 2-inputWidth : '20px' , 2-inputHeight: '10px', 2-color : 'blue', 3-inputWidth : '60px' , 3-inputHe ...

Always keep your phone in landscape orientation for optimal website viewing

Currently, I am facing an issue with my website where it functions perfectly on mobile devices in landscape orientation but elements get distorted when viewed in portrait mode. Is there a method to ensure that the website is always displayed in landscape ...

Trim the final digits from the arrays

I have an array that contains various strings: var arr = ['1234','23C','456','356778', '56'] My goal is to filter out array elements that are less than 3 characters or more than 4 characters. The resultin ...

What is the best way to send data to the server using Vue.js?

I don't have much experience with JavaScript or web programming, so please bear with me if my question seems basic. Currently, I am using Vue to create the front end of my project. I also have a server that offers a REST interface. This REST interfac ...

In HTML, data can be easily accessed, however, JavaScript does not have the same

When trying to access the 'data' element in a JSON object, I have encountered an issue. The element is accessible when called from HTML, but not when called in JavaScript. HTML: <p>{{geoJson.data}}</p> JavaScript: let scope; let d ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

The SmoothShading feature of THREE does not alter the geometry

I am having trouble with smooth shading on my model - the polygons are still clearly visible and switching between smooth and flat shading in the three.js inspector isn't making a difference. The OBJ file contains vertex normal data, so I don't t ...

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...