What is the best way to modify a specific row in a Vue.js array?

Would you happen to know the correct way to refresh a specific row from a vueJS array list without having to reload all the data?

In this particular scenario, we are dealing with a phone list.

<template>
    <table class="table">
        <tr v-for="phone in phones">
            <td @click="edit(phone.id)">
                {{phone.number}}
            </td>
            <td class="pointerCursor" @click="edit(phone.id)">
                {{phone.comment | truncate(90)}}
            </td>
        </tr>
    </table>
</template>

<script>
    export default {
        data () {
            return {
                phones = [
                    {id:1, number: '001 656 88 44', comment:''},
                    {id:2, number: '610-910-3575 x2750', comment:'Quod odit quia'},
                    {id:3, number: '536.224.2639 x714', comment:'primary phone'},
                    {id:5, number: '0034 556 65 77', comment:'home phone phone'},
                ]
            }
        },

        methods: {
            edit(id) {
                // update using an api that returns the updated data.
                var updatedPhone = update(id)

                // what is the best approach for updating without reloading the entire phone list?
                // ...
            }
        }
    }
</script>

PS: Please note that this example code is solely for illustration purposes regarding the issue at hand.

Answer №1

const idx = this.smartphones.findIndex(s => s.serial === serial);
this.smartphones.splice(idx, 1, updatedSmartphone)

If the platform you're targeting does not support the findIndex method for arrays, you can use alternative methods to locate the current index. One option is to pass the smartphone object itself instead of its serial number.

edit(smartphone) {
    const idx = this.smartphones.indexOf(smartphone);

    // utilize an API that returns the updated information.
    var updatedSmartphone = update(smartphone.serial)

    this.smartphones.splice(idx, 1, updatedSmartphone)
}

In either scenario, Vue will identify the change and handle the rendering process automatically.

Answer №2

Utilize the pre-existing index generation feature:

    <tr v-for="(phone, idx) in phones">
        <td @click="edit(idx)">
            {{phone.number}}
        </td>
        <td class="pointerCursor" @click="edit(idx)">
            {{phone.comment | truncate(90)}}
        </td>
    </tr>

Within the edit function:

    methods: {
        edit(idx) {
            phone = this.phones[idx];

            // Update by calling an API that returns the updated data.
            var updatedPhone = update(phone.id)

            // How can we refresh the phone list with the updated information?
            this.phones.splice(idx, 1, updatedPhone)
        }
    }

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

What are some solutions for managing SubPixel Handling issues on an iPhone?

Issue: I am currently in the process of developing a PhoneGap/Cordova app for both iOS and Android using jQuery Mobile. To incorporate a calendar feature into my app, I decided to create my own rather than use existing plugins due to not finding any that m ...

Retrieving an Element that Triggered an HTTP GET Request in Node.js with Express

In my Express front-end development project, I have a table with rows containing links that trigger GET requests. These requests are sent to the back-end, which is created using node.js, in order to retrieve files corresponding to each row. All links follo ...

Strange behavior observed when converting Javascript array to object

Check out this code: let example = []; example.someData = "wow"; console.log(example); // output: [ someData: 'wow' ] console.log(JSON.stringify(example)); // output: [] console.log(example.someData); // output: wow console.log(JSON.stringi ...

Converting a data-attribute list into an array

My current setup includes an image with the following properties: <img id="img" data-list="['image2.jpg', 'image3.jpg', 'image4.jpg']" src="image1.jpg"> I am wondering how I can extract the list of images from the data ...

How can I swap a string for a symbol in JavaScript?

Is there a way to convert the text @abc some text here to <a href="some_url">@abc</a> some text here using JavaScript? Are there any libraries that can help with this task? ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

fa icons moving the elements aside

I'm attempting to design a navigation menu with tabs, but I'm facing an issue where the tabs containing "fa icons" are consuming too much space, causing other elements to be shifted to the right or below (if there were more lines). How can I pre ...

What is the process for updating the values of all objects within an array of objects using Javascript?

I am attempting to update the values of car in all objects within an array called data with the values from newData. Here is my code snippet: import "./styles.css"; const data = [ { id: 1, car: "Toyota 2020", owner: "BM" }, ...

Upon removing an element, the button click event fails to trigger

I recently created a div that looks like this <div id="hidden"> <img src="photos/Close-2-icon.png" width="16" height="16"> <input id="add" value="Add field" type="button" > <input type='button' id=&a ...

What is the best way to apply a hover effect to a specific element?

Within my CSS stylesheet, I've defined the following: li.sort:hover {color: #F00;} All of my list items with the 'sort' class work as intended when the Document Object Model (DOM) is rendered. However, if I dynamically create a brand new ...

experiment with jest and react-testing-library for testing functions

I'm having trouble accessing a method inside a functional component in React using Jest and react-testing-library. I attempted to use enzyme, but it seems like everything is shifting towards RTL instead. import React from "react"; const simpleCompo ...

Timing events in javascript based on frames per second

Currently, I am working on a mini-game that requires some animations to be implemented in the form of frames per second. Here is my current approach: var loadCount = 0; var ticks = 15; function loadingLoop() { loadCount++; } switch (loadCount) { ...

Slider Volume with jQuery

Struggling to find a solution for this issue. Seeking some assistance. My goal is to create a basic volume slider. So, the orange section represents my volume slider. This is the jQuery code I am using: var mouseIsDown = false; $("#volSlider").on("mou ...

Having difficulty setting a value for a tooltip with replaceWith() function

When using jQuery's .replaceWith() method to insert new DOM contents, I noticed that all content gets replaced except for the value of the title. Even though I tried different approaches, the tooltip only displays {{descriptions.title}} instead of the ...

Configuring Braintree Client with JS v3 - encountering a null payment_method_nonce causing issues with form submission

I have successfully integrated Braintree into my Laravel 5.2 app using JS v2 client setup, but now I want to upgrade to v3. I have customized the code from the docs as follows: <form id="checkout-form" action="/checkout" method="post"> <div id= ...

Issue with Server: Unforeseen symbol < found in JSON at position 1

Explanation I've encountered an issue with a JSON file displaying the message "Error with Server SyntaxError: Unexpected token < in JSON at position 1". I've examined the file, checked its encoding, but couldn't identify any vi ...

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

Transferring JSON information from JavaScript to PHP

I have searched for various solutions, but have not found one yet. I am stuck with the following piece of code and my suspicion is that the jsondata arriving at the PHP script is empty. Unfortunately, I am clueless on how to debug this issue as the script ...

Having difficulty formulating a MongoDB query that includes a subquery

I have a dataset structured as follows: { "id": "02741544", "items": [{ "item": "A" }] }, { "id": "02472691", "items": [{ "item": "A" }, { "item": "B" }, { "item": "C" }] }, { "id": "01316523", "items": [{ "item" ...

Utilizing React with Material UI, implement a Select component while disabling the scroll lock and ensuring the menu is positioned relative to

import React from "react"; import "./styles.css"; import Input from "@material-ui/core/Input"; import MenuItem from "@material-ui/core/MenuItem"; import FormControl from "@material-ui/core/FormControl"; import Select from "@material-ui/core/Select"; cons ...