Adding new elements to an array does not activate the reactivity of Vue

After discovering that editing objects within an array doesn't function properly in vue.js due to its limitations, I tried using vue.set to resolve the issue, but it's proving to be quite challenging for me.

Let's take a look at the sample data. The main object is named resource, containing power_generator_groups within it, and inside the power_generator_groups are power_generators.

{
  "id": 5,
  "bg_member_id": 1,
  "code": "G0633",
  "name": "namex1",
  "power_generator_groups": [
    {
      "id": 1,
      "resource_id": 5,
      "code": "GC033",
      "power_generators": [
        {
          "id": 1,
          "power_generator_group_id": 1,
          "code": "XXXXX",
          "name": "test",
          "contract_number": "00000003",
          "supply_max": 1000
        },
        {
          "id": 2,
          "power_generator_group_id": 1,
          "code": "XXXXX",
          "name": "test",
          "contract_number": "00000003",
          "supply_max": 1000
        },
        {
          "id": 3,
          "power_generator_group_id": 1,
          "code": "XXXXX",
          "name": "test",
          "contract_number": "00000003",
          "supply_max": 1000
        }
      ]
    },
    {
      "id": 2,
      "resource_id": 5,
      "code": "GC033",
      "contract_number": "065C001",
      "power_generators": [
        {
          "id": 4,
          "power_generator_group_id": 2,
          "code": "XXXXX",
          "name": "test",
          "contract_number": "00000003",
          "supply_max": 1000
        }
      ]
    }
  ]
}

Now, moving on to my Vue file:

<template lang="pug">
  .wrapper
    .animated.fadeIn
      b-container(fluid='')
        ... (Vue template code)
    </template>

    <script>
    import Vue from 'vue';
    export default {
        props: {...},
        data() {
            return {...
                items: {}};
        },
        mounted() {},
        computed: {},
        methods: {...}
    }
</script>

Answer №1

Use of Vue.set is necessary only when the power_generator_groups lack the power_generators property, as Vue cannot detect its addition otherwise. Assuming your template is problem-free (which was not shown), update your addPowerGenerator method:

addPowerGenerator(index) {
  console.log(index)
  console.log(this.item)
  const pgg = this.item.power_generator_groups[index];
  const pgs = pgg.power_generators || Vue.set(pgg, 'power_generators', []);
  pgs.push(
    {
      "code": "",
      "name": "",
      "contract_number": "",
      "supply_max": "",
    }
  )
}

Vue.set will return the newly created property, ensuring that pgs contains the correct reference in that scenario.

Apply the same logic to the updated method:

addPowerGeneratorGroup() {
const pggs = this.item.power_generator_groups || Vue.set(this.item, 'power_generator_groups', []);
  pggs.push(
    {
      "resource_id": this.item.id,
      "name": "",
      "code": "",
      "contract_number": "",
      "power_generators": []
    }
  )
}

Refer to this mockup where I have made an assumption that this.item denotes the resource itself. I included a third group without the power_generators property for testing purposes.

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

Guide to utilizing various functions, with equations, within a specific scope in angularJS

myApp.controller('incomeController', ['$scope', function($scope) { $scope.pay = 0; $scope.hours = 0; $scope.tax=0.19297; $scope.total = function() { return $scope.pay * $scope.hours;} $scope.taxTotal ...

Access Denied: Origin Issue with OAuth2

I am requesting an authorization code from the OAuth2 Server in order to authenticate a user with my Microsoft App. For more information, I consulted this document. This is my attempt to make the call: function httpGet(){ var theUrl = "https://lo ...

Is it possible to receive returned string values using fetch()?

I have implemented a fetch method in my separate register.js file to handle registration on the front end. However, I am encountering an error when trying to POST the data and receive the following message in the browser console: "Uncaught (in promise) Syn ...

My Angular custom libraries are having issues with the typing paths. Can anyone help me troubleshoot what I might be doing

After successfully creating my first custom Angular library using ng-packagr, I encountered an issue where the built library contained relative paths specific to my local machine. This posed a problem as these paths would not work for anyone else trying to ...

Revolutionize Your App with React Native's Interactive Bottom Sheet Option

Hello there! I am trying to create a FlatList with multiple items, each of which should trigger a bottom-sheet when clicked. I want to make this dynamic but I'm encountering an error. TypeError: undefined is not an object (evaluating `_this[_reactNat ...

Determine if a JSON object is void

Using jQuery, I am checking whether the object returned from an AJAX call is empty or not. In the first example, the AJAX call is successful and returns some data. console.log("obj before JSON parse:", response); var test = $.isEmptyObject(response); con ...

Creating a tab component using vanilla javascript

I am facing an issue with my tab component in plain JavaScript. The content displays correctly in debug mode, but after compilation, it does not show up on the browser. Additionally, when I select a tab, the 'activeNav' class is applied to indica ...

I am unable to display the content even after setting `display: block` using the `.show()`

Hello there, I have attached my javascript and html code. While in debug mode, I can see that the CSS property 'display: none' changes to 'display: block', but for some reason, the popupEventForm does not open up. Any suggestions on why ...

Checking the conditional styling implemented with Material UI makeStyles: a step-by-step guide

For the past few weeks, I've been working on a React app where I heavily rely on Material UI components. One particular component changes its style based on the values of its props. To achieve this, I used the following approach: const useStyles = ...

Sending a variable to an AngularJS factory

I am currently working on a select list that looks like this: <select name="make" class="form-control" ng-model="selectCity"> <option value="Kannur">Kannur</option> <option value="Agra">Agra</option> <option va ...

"Terminate the current window that is open within the handler for the XMLHttpRequest

Currently, my approach involves using Javascript and Ajax to retrieve data and display it in a new window. I am encountering an issue where I am trying to close the window in the OpenFileWindow() function before opening a new one, but I am facing a permiss ...

I am in desperate need of assistance to grasp the concept of writing a class (including the declaration and definition) solely by analyzing a main program and the corresponding sample output

I've been analyzing an example and attempting to decipher the process of writing the .h and .cpp files based on observation of the main file and its output. In this case, there is a class named Flex: #include <iostream> #include "flex.h" using ...

Utilizing jQuery for asynchronous image uploading

Just started learning jQuery and I'm having trouble uploading a jpg image file using the ajax method. It seems like it's not working properly. Can anyone guide me through this process? HTML <form action="" method="POST" enctype="multipart/fo ...

Creating a fresh shortcut on the selenium IDE

Is there a way to customize shortcuts in Selenium IDE by modifying its code? For instance, I would like to set the shortcut ctrl + p for the action run test case, similar to how the save action is assigned ctrl + s. I've searched for the JavaScript ...

Quick question about utilizing Ajax with spans

<span name = "menu"> <!-- javascript here --> <!-- content loaded via ajax --> </span> <span name = "content"> <!-- content loaded via ajax --> <!-- updated by buttons from the menu--> </span> Seeking a ...

A function designed to retrieve all nearby values within a list

After spending quite some time trying to tackle the problem at hand, I find myself stuck. I am dealing with a list of various values, such as: list1 = (17208, 17206, 17203, 17207, 17727, 750, 900, 905) I am looking to create a function that can identify a ...

Node.js tutorial: Matching aggregations by UserId

I have been developing a sample application in React where I have utilized aggregations. One of the functionalities involves implementing a query based on user ID that matches the status and retrieves the MAXDate and MINDate fields. How can I retrieve the ...

In search of the most efficient method for integrating an AJAX-powered TreeGrid feature

Can anyone recommend an Ajax/TreeGrid implementation that meets the following criteria: Must support server side sorting Should be able to load leaf nodes on demand, meaning only children of open nodes are loaded Needs to support paging so that nodes are ...

What is the best way to capture videos using Safari?

Hey there! I've set up the browser camera on my website for users to record live tests. It's been working great on Chrome and Firefox using MediaRecorder, but unfortunately, Safari isn't cooperating. Does anyone know of an alternative to Me ...

Subdomain redirection issue with express-subdomain for localhost GET requests

In order to manage requests to specific subdomains, I am utilizing a package in express.js called express-subdomain. From my understanding, the subdomain constructor function requires an express router object that I pass from an exported router module. M ...