The DOM fails to reflect changes in the data variable in VueJS

I am facing an issue while trying to update an array of arrays and display it as a reactive variable, however the DOM does not seem to reflect those changes.

To achieve this, I have two components - a parent component and a child component:

Parent Component: The parent component initializes the child component and passes a method (fetchOptionsFn) as a prop. This method fetches data and updates an array located in the child component.

<component :is="DynamicDataPairForm"
            :fetchOptionsFn="fetchOptionsFn"

fetchOptionsFn (search, loading, selectOptionsArray, index) {
      if (search.length >= 3) {
        pptDocumentLibraryService.findByTitle(search).then(res => {
          selectOptionsArray[index] = res.data
        }).catch(err => console.log(err))
      }

Child Component: The child component defines an empty array, sets up a SELECT element in the DOM, and when a search is performed on it, the array gets modified by the function inherited from the parent.

<tr v-for="(entity,index) in filteredEntityList" :key="entity[entityIdField]">
<v-select
:options="selectEntityArray[index]"
@search="(search, loading) => {
fetchSelectEntityOptions(search, loading, index) }"
/>
</tr>

props: {
 fetchOptionsFn: { type: Function, required: false, default: () => {} },
},
data: {
 selectEntityArray: []
},
methods: {
 fetchSelectEntityOptions (search, loading, index) {
      this.fetchOptionsFn(search, loading, this.selectEntityArray, index)
    }
}

The issue arises when the function fetchSelectEntityOptions is called, but the array selectEntityArray does not change in the DOM.

https://i.stack.imgur.com/IGP2N.png https://i.stack.imgur.com/WBP5V.png

Any suggestions or thoughts on how to resolve this problem would be greatly appreciated!

Answer №1

Vue 2 comes with some important considerations around change detection that you should be aware of...

There are certain changes to an array that Vue is unable to detect:

  1. Directly setting an item by index, for example: vm.items[indexOfItem] = newValue
  2. Modifying the length of the array, for instance: vm.items.length = newLength

If you encounter a situation like this, you can make the following adjustment:

selectOptionsArray[index] = res.data

Update it to:

Vue.set(selectOptionsArray, index, res.data)

Answer №2

It appears that you may need to establish an index data property within the child component to clarify which index is being referenced in the

:options="selectEntityArray[index]"
attribute. Additionally, ensure to assign the index value in the fetchSelectEntityOptions function.

You can modify your code like so:

<v-select
:options="selectEntityArray[index]"
@search="(search, loading) => {
fetchSelectEntityOptions(search, loading, index) }"
/>

props: {
 fetchOptionsFn: { type: Function, required: false, default: () => {} },
},
data: {
 selectEntityArray: [],
 index: null,
},
methods: {
 fetchSelectEntityOptions (search, loading, index) {
      this.index = index;
      this.fetchOptionsFn(search, loading, this.selectEntityArray, index);
    }
}

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

JQuery Ajax encounters a 500 error message due to an internal server issue

I'm currently using the jQuery library to send an ajax request to a PHP file. Initially, everything was working perfectly fine with a relative path like this: url:"fetch_term_grades.php", However, when I modified the path to be more specific like th ...

Three.js: Spherical boundary of an object that has been resized

When working with a collection of 3D shapes such as pyramids, cubes, octahedrons, and prisms, I encountered an issue with building described spheres around them. While it's straightforward to create the spheres using geometry.boundingSphere due to its ...

Reverse a filter within an ng-repeat loop - AngularJS

I have a question that I haven't found the answer to yet. Here is the issue I'm facing: The JSON data I am working with has this structure: [{ "batch_queue_name": "Batch One", "start_date": "12/01/2016 10:18 P.M.", "end_date": "12/03/2016 ...

JavaScript does not alter the text box for the default dropdown value

My webpage has three elements: a text box named txtSubTotal, a drop-down menu named discount, and another text box called txtGrossTotal. The txtSubTotal updates when the user clicks on the 'ADD' button, while the txtGrossTotal updates based on th ...

Guide to encoding data using a multidimensional array in JSON format

I have an array that looks like this: array { [0] => {"ID":"343","name":"John","money":"3000"} [1] => {"ID":"344","name":"Erik","money":"2000"} [2] => {"ID":"346","name":"Ronny","money":"3300"} } My goal is to transfer this data from ...

Interactive table created with DataTables that automatically updates the dynamic JSON data source whenever changes are made to the table

Using the Datatables plugin, I am dynamically populating a table with HTML rendered from a JSON array. However, I need the table to update the model (datasource) stored client-side whenever an edit is made. When navigating to a new page on the table, it s ...

JavaScript isn't functioning properly after UserControl is loaded via Ajax

Thank you, Stilgar for helping me solve my issue. I created a javascript file and placed all my code in it. After adding this file to the UserControl and retrieving the UserControl's html, I used $("#DivID").html(UserControlHTML). Now everything is wo ...

Having issues with socket.io connectivity on my Node server

I am setting up my node server to update all connected clients with real-time information. However, when I run the code provided below, the io.sockets.on('connection') callback keeps firing constantly, flooding the console with the message Client ...

What is the best method to fetch a specific post from supabase for showcasing in a dynamic Route with Nextjs14?

I'm currently working on a Next.js application where I am fetching posts from a Supabase database. Everything works fine when retrieving all posts, but when trying to retrieve a single post dynamically using the ID, the screen displays null. Here&apos ...

Utilize AJAX to fetch and display the response from a Node JS route directly onto an HTML page

At the moment, I am retrieving client-side HTML/JS inputs (var1 and var2) which are then sent to server-side Node JS. The input values are stored in variables through an AJAX post call made to a specific route. What I want now is to define the values of v ...

Filter the ng-repeat list dynamically by triggering ng-click event

I am currently developing an application on that requires users to be able to filter a list of credit cards by clicking on filters located on the interface, such as filtering for only Amex cards or cards with no fees. Although I have successfully bound t ...

Storing Ember.js Views for Faster Loading

Exploring the features of AngularJS and Ember, I am curious to know if Ember has the capability to cache views instead of just loading/reloading them. For instance, if I have tabs with templates like "abc.html," "def.html," and "ghi.html," can I create div ...

Enforce a limit of two decimal places on input fields using jQuery

Looking to limit an input field so that users can only enter numbers with a maximum of two decimals. Is it possible to achieve this using jQuery? Any way I could utilize the jQuery toFixed() function for this purpose? Thank you in advance! ...

When the parent div contains at least four divs, show the scroll arrow containers

In my code, there is a parent div that holds multiple child divs. If the number of child divs within the parent div exceeds 4, I want to show the scroll arrow containers. If it's less than 4, then those arrow containers should not be displayed. The ...

How can I enable a constant condition in eslint?

I have encountered an issue with my package.json configuration. Here is the current eslintConfig generated: "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/essential", "@vue/standard" ...

How do I transform the date "Tue Nov 26 2019 16:00:00 GMT-0800" into the .NET JSON date format "/Date(1574812800000)/"?

I am looking to convert a date from ISO format to .NET JSON date format using JavaScript. For example, I want to change "Tue Nov 26 2019 16:00:00 GMT-0800" to "/Date(1574812800000)/". ...

Capture the response from an AJAX request and store it in a JavaScript variable

I've been struggling to find a solution for this issue for quite some time now without any success. Here's what I'm trying to accomplish: I need to retrieve an array from my PHP file so that I can utilize it in my JavaScript code. Example. ...

Adjust webpage display with JavaScript

Utilizing the mobile-first approach of Zurb Foundation, I successfully created a responsive design. However, my client now requires a direct link labeled "View desktop version" in the footer for when the website is accessed on mobile devices or tablets. T ...

The on-screen keyboard using JQuery and CSS is not working properly on an HTML redesign

UPDATE - Check out the modified version here: https://codepen.io/anon/pen/wZQjQy Here is the original for reference: https://codepen.io/anon/pen/YMRLBN (had to utilize CodePen, as simply adding a snippet here doesn't link the CSS) I essentially copie ...

"Bootstrap is functioning properly on my local environment, but it seems to

Utilizing the MVC framework and bootstrap has been successful for optimizing my website locally. However, when I upload it to the server, none of the CSS is being rendered. Additionally, the front page, meant to be a carousel slider, appears as a vertical ...