Vue reactivity fails to detect newly added properties to an element within an array

Can someone help me with an issue I'm having where a template element is not reacting to an added property of an array element? Here's the example:

<div v-for="user in users"
     v-bind:key="user.id"
     v-bind:name="user.name">
     {{user.name}}
     <div class="warn" v-if="user.hasWarning">Warning!</div>
</div>

I want to display a warning whenever hasWarning: true is added to user

data:() {
  users: [
    {id: 1, name: "Foo"}
  ]
},
methods:{
  showWarning: function(id) {
    users.forEach(user => {
      if (user.id == id) {
        user.hasWarning = true;
      }
    });
  }
}

Even though I can see hasWarning being added to the user from both the console and Vue developer tools after calling showWarning(id), it doesn't render

<div class class="warn" v-if="user.hasWarning"..
. It works fine if my user is set up as
{id: 1, name: "foo", hasWarning: false}
, so why isn't it working for the added property? Should I avoid this approach altogether?

Answer №1

Make sure to utilize the this.$set method for adding new properties. For more details, refer to the documentation: https://v2.vuejs.org/v2/api/#vm-set

Here's a sample implementation:

<template>
  <div>
    <div v-for="user in users" v-bind:key="user.id" v-bind:name="user.name">
      {{ user.name }}
      <button @click="showWarning(user.id)">showWarning</button>
      <div class="warn" v-if="user.hasWarning">Warning!</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data: () => ({
    users: [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }],
  }),
  methods: {
    showWarning(id) {
      let user = this.users.find(user => user.id == id);
      this.$set(user, 'hasWarning', true);
    },
  },
};
</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

Following an AJAX request, jQuery.each() does not have access to the newly loaded CSS selectors

Note: While I value the opinions of others, I don't believe this issue is a duplicate based on the provided link. I have searched for a solution but have not found one that addresses my specific problem. Objective: Load HTML content to an element u ...

Errors found during compilation when running the npm start command

After choosing to develop an app with React using VS Code, I initiated the process by running npm create-react-app ./, which was a success. However, when I proceeded to execute the command npm start, it resulted in compilation errors related to files suc ...

Retrieve the value associated with the data attribute of the chosen dropdown option

I need to extract the custom data attribute from the chosen option of a dropdown menu and insert it into a text box. This will be the second data attribute I'm working with. I plan to implement code that will run whenever the user changes the option ( ...

Struggling with React integration of AdminLTE3 sidebar treeview?

I have a requirement to create a React sidebar with a category 'Staff' that, when clicked, reveals three subordinate categories. Below is the code snippet: import React, { Component } from "react"; export default class Sidebar extends Componen ...

Error encountered in Nuxt.js when reloading page due to undefined data

Currently in the process of developing a versatile application with Nuxt.js, I am utilizing a fetch hook and vuex store to retrieve data from an API on most of the pages. I've encountered errors when reloading or refreshing a page, as well as when nav ...

Using Jquery to Retrieve the Attribute Value from an HTML Element

I am currently developing an interactive online quiz application that is organized by chapters, with each chapter having its own quiz. Users can navigate through the chapters via a menu and start quizzes by clicking on a button after loading the chapter co ...

Utilize JQuery's .load() function to transmit JSON data to your Flask server

I am attempting to utilize JQuery's .load() function in order to transmit data to my Flask server and then, with that information, display a <div> that is loaded into the element making the request. This is what my code snippet looks like: $(&qu ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

Eliminate repetitive elements from an array using a specific merging algorithm

Here's a thought I have: If we have an array of objects like this: [ { "name": "Kirk", "count": 1 }, { "name": "Spock", "count": 1 }, { "name": "Kirk", "count": 1 } ] I would l ...

TabPanel with Grid component causes Error: The server-rendered UI does not match the initial UI, resulting in failed hydration

After completing all the necessary steps and transferring all the files from nextjs-with-typescript, everything seemed to be in order until I tried adding Grid inside the TabPanel in the code snippet below: import * as React from 'react'; Tabs fr ...

Failure to trigger on change event

I am struggling with dynamically generating input fields of the file type. Unfortunately, when I attempt to access its triggered event, nothing seems to happen. Below is the code snippet for the dynamic input file: <div id="documentlist" class="col-lg ...

How can I showcase the index of `<tr>` and `<td>` elements in a dynamically generated table

How can I print the index of table rows and data on click in javascript? <html> <head> <title>Table Creation</title> <script language="javascript" type="text/javascript"> function createTable() { ...

Revising HTML content when Angular array is modified

I have a code snippet below where I am updating the value of an object in the first item of an array. However, I'm struggling to find a way to "refresh" the HTML view so that the changes are immediately reflected on the browser. var dataArr ...

Having trouble installing sqlite3? Encounter an issue like this: "srcdatabase.cc(35): error C2248: 'Napi::Env::DefaultFini': cannot access private member declared in class 'Napi::Env'"?

Encountering issues while trying to install sqlite3 for a Strapi app I've attempted using yarn to install sqlite3 in various ways, but to no avail. Below is the error log: Error message: Issue with installing sqlite3 when creating a Strapi app (..& ...

The initial value set for the innerHTML property of a div element

I have a requirement in my application where I need to confirm if the container div is empty before adding specific text elements to it. The innerHTML of this div is frequently created and removed within the app, so it's crucial to validate its emptin ...

How can JavaScript determine if this is a legitimate JS class?

I'm currently in the process of converting a React.js project to a next.js project. In my project, there's a file named udf-compatible-datafeed.js. import * as tslib_1 from "tslib"; import { UDFCompatibleDatafeedBase } from "./udf-compatibl ...

Identical manipulator distinct infusion

I am looking to create multiple controllers that share the same logic, with only differences in injections. One way to achieve this is by creating controllers using a common function like so: var controllerFunc = function($scope, service) { $scope.se ...

Can AJAX be considered a backend tool for retrieving data from servers?

I'm curious to find out if ajax is primarily used as a backend technology for retrieving data or if it's mainly considered a frontend tool. My attempts to research this on Google have not yielded a definitive answer. ...

The Express server is failing to deliver a response to the client when using the fetch method

Currently, I am utilizing express for the server side of my project. To send a post request from the client to the server, I am using fetch. The data that I am sending to the server is being successfully transmitted and displayed. However, I am encounteri ...