Manipulating arrays within Vuejs does not trigger a re-render of table rows

I have successfully generated a user table using data retrieved from an ajax request. The table has a structure similar to this: [Image of Table][1]

Now, when an admin makes changes to a user's username, I want the respective row to update with the new information, specifically the user's first name and last name.

Although I have properly implemented the table and the models are functioning correctly, I am facing an issue with updating the target row with the edited data. How can I achieve this?

I have tried the following methods, but they did not work:

  • How to update a particular row of a vueJs array list?
  • https://v2.vuejs.org/v2/guide/list.html#Caveats
  • I have ensured that each row has a unique key
  • Attempted to update the listOfUsers using Vue.set()
  • Also tried using Vue.set() instead of splice

Below is a snippet of my parent vue component code with irrelevant details removed:

TEMPLATE:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email Address</th>
            <th>Created</th>
            <th>Stat</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="(user, index) in listOfUsers" :key="'row' + user._id"> 
            <td>{{user.first_name + ' ' + user.last_name}}</td>
            <td>{{user.email}}</td>
            <td>{{user.created}}</td>
            <td>
                <a v-if="user.confirmed" @click="determineButtonClicked(index, 'confirm')"></a>
                <a v-else @click="determineButtonClicked(index, 'unconfirm')"></a>
            </td>
            <td class="buttonCase">
                <a @click="determineButtonClicked(index, 'info')"></a>

                <a v-if="user.blocked" @click="determineButtonClicked(index, 'blocked')"></a>
                <a v-else @click="determineButtonClicked(index, 'block')"></a>
        
                <a v-if="user.enforce_info === 'required'" @click="determineButtonClicked(index, 'enforceInfoActive')"></a> 
                <a v-else-if="user.enforce_info === 'done'" @click="determineButtonClicked(index, 'enforceInfoChecked')"></a>
                <a v-else @click="determineButtonClicked(index, 'enforceInfo')"></a>

                <modal v-if="usersList[index]" @toggleClickedState="setState(index)" @editUser="edit(index, $event)" :id="user._id" :action="action"></modal>
            </td>
        </tr>
    </tbody>
</table>

SCRIPT

<script>
    export default {
        created: function() {
            let self = this;
            $.getJSON("/ListOfUsers",
            function(data){
                self.listOfUsers = data;
            });
        },
        data: function() {
            return {
                listOfUsers: [],
            }
        },
        methods: {
            edit(index, update){
                let user = this.listOfUsers[index];
                user.firstName = update.firstName;
                user.lastName = update.lastName;
                
                // this.listOfUsers.splice(index, 1, user)
                this.listOfUsers.$set(index, user)
            }
        }
    }
</script>

Thank you for your valuable time and assistance! [1]: https://i.sstatic.net/lYQ2A.png

Answer №1

One reason Vue may not be updating in your edit method is because the object itself is not being replaced. While properties of the object do change, Vue is specifically looking for a change in the object reference.

To ensure that the array detects a change in the actual object reference, you need to replace the object rather than just modifying it. While I may not know the exact way you wish to approach this, the provided fiddle showcases this issue so that you can find a workaround: http://jsfiddle.net/tga50ry7/5/

In summary, if you update your edit method as shown below, you will likely see the re-render happening in the template:

methods: {
   edit(index, update){
      let currentUser = this.listOfUsers[index];
      let newUser = {
         first_name: update.firstName,
         last_name: update.lastName,
         email: currentUser.email,
         created: currentUser.created
      }

      this.listOfUsers.splice(index, 1, newUser)
   }
}

Answer №2

If you want to give it a shot, try following this code snippet:

<script>
    export default {
        created: function() {
            let self = this;
            $.getJSON("/ListOfUsers",
            function(data){
                self.listOfUsers = data;
            });
        },
        data: function() {
            return {
                listOfUsers: [],
            }
        },
        methods: {
            edit(index, update){
                let user = this.listOfUsers[index];
                user.firstName = update.firstName;
                user.lastName = update.lastName;

                // this.listOfUsers.splice(index, 1, user)
                this.$set(this.listOfUsers,index, user)
            }
        }
    }
</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

Having trouble with querySelector or getElementById not functioning properly?

Currently, I am in the midst of developing an experimental web application that features a quiz component. For this project, I have implemented a Python file to handle the questions and quiz functionalities. However, I have encountered an issue with the Ja ...

Receive live feedback from shell_exec command as it runs

I have been working on a PHP-scripted web page that takes the filename of a previously uploaded JFFS2 image on the server. The goal is to flash a partition with this image and display the results. Previously, I had used the following code: $tmp = shell_ex ...

"Encountered an Ajax Error while appending request parameters to the same link during a

I can't figure out why my ajax request is sending to the same link instead of the specified url. It's only this ajax request on the entire page that is behaving strangely. Can anyone shed some light on this issue? $(document).ready(function(){ ...

Element UI: Triggering an event when the sort caret is clicked

Is it possible to trigger an event when the sorting carets are clicked on a table with sortable columns, ideally with the same parameters as the header-click event? I am able to emit an event by clicking on the header of any sortable column (header-click) ...

finding the index of a particular checkbox in a list

I am working with a list of checkboxes that are dynamically created using JavaScript, each contained within its own separate div element. I need to determine the position number of a specific checkbox within all checkboxes sharing the same class within a p ...

Navigable Vuetify Tabs with routing capabilities

Within my Vue application, I have a page that contains various tabs. My goal is to display different tabs based on the routes being accessed. To achieve this functionality, I followed an answer provided in this link. Overall, it's working well! I ca ...

Simple steps to add a click event listener to every element within a div

I need to assign a click handler to multiple elements and perform different actions based on which one is clicked. To illustrate, I can create an alert displaying the class of the button that was clicked. The elements I am working with have a similar str ...

I'm having trouble with my react-big-calendar not updating when I switch between day, month, or week views -

Why won't my calendar change to the week view when I click on that section? https://i.stack.imgur.com/gh2aO.png In the screenshot above, my default view is set to month, but when I attempt to switch to week, it only highlights the option without cha ...

I'm having trouble installing puppeteer

I tried running the command npm i --save-dev puppeteer to set up puppeteer for e2e testing. Unfortunately, an error occurred during installation: C:\Users\Mora\Desktop\JS\Testing>npm i --save-dev puppeteer > <a href="/cd ...

Node.js and Express - Dealing with Callbacks that Return Undefined Prematurely

I've hit a roadblock with this issue that's been haunting me for weeks. The first function in my code queries a MySQL database and returns a response, which is then processed by the second function. The problem lies in the fact that JavaScript ...

Is the availability of XMLHttpRequest constant?

When using XMLHttpRequest to retrieve data from the server with Javascript, is it necessary to include conditional checks for the specific browser being used? Is the code snippet below considered standard practice when working with XMLHttpRequest? if (w ...

What is the best way to organize objects by their respective dates?

I am retrieving data from a database and I would like to organize the response by date. I need some assistance in grouping my data by date. Below is an example of the object I have: var DATA = [{ "foodId": "59031fdcd78c55b7ffda17fc", "qty" ...

I am having trouble embedding YouTube videos with my code

Need a fresh pair of eyes on this code. Everything looks correct to me, but it's not functioning as expected. The entries are results from a search. function displayVideos(data) { var feed = data.feed; var entries = feed.entry || []; va ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Update the directive automatically whenever a change occurs in the root scope property

I am facing an issue with a directive that generates a random number. My goal is to reload or refresh this directive when a checkbox is toggled. Below is the code I have been using, but unfortunately, it's not working as expected. var app = angular. ...

What is the maximum string length allowed for the parameter accepted by JavaScript's JSON.Parse() function?

Is there a maximum string length limit for the parameter accepted by JavaScript's JSON.Parse()? If I were to pass a string that surpasses this expected length, will it result in an exception being thrown or prevent the function from returning a valid ...

Utilizing jQuery and AJAX, execute a PHP query based on the user's input and showcase the query's outcome without reloading the page

For the past 24 hours, I've been on a quest to find a solution. Although I've come across similar inquiries, either the responses are too complex for my specific scenario (resulting in confusion) or they are of poor quality. The crux of my issue ...

Utilizing Prototype in Node.js Modules

Currently, I am working on a project involving multiple vendor-specific files in node. These files all follow a similar controller pattern, so it would be more efficient for me to extract them and consolidate them into a single common file. If you're ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

Tips for preventing multiple occurrences on a single object?

Currently, I am working on creating a preview of an image when a link is entered into a text box. Utilizing jQuery, I am able to display the image preview in a <div>. In cases where there are multiple images, I am attempting to implement a navigation ...