Resetting dynamic form changes in Vue.js explained

Currently, I am using a template like this:

<div>
    <div v-for="(item, key) in items" :key="key">
        <div>
            <input type="text" :value="item.title">
        </div>
        <div>
            <input type="text" :value="item.description">
        </div>
        <div class="actions">
            <button type="button" @click="discardChanges(item)" :disabled="!itemChanged">Discard changes</button>
            <button type="button" @click="sendChanges(item)" :disabled="!itemChanged">Save</button>
        </div>
    </div>
</div>
<script type="text/javascript">
    export default {
        data() {
            return {
                itemChanged: false,
                items: [
                    {
                        title: "Apple",
                        description: "The biggest company in the world"
                    },
                    {
                        title: "Amazon",
                        description: "The biggest online store in the USA"
                    },
                ]
            }
        },
        methods: {
            sendChanges(item) {
                // Send API request to update item
            },
            discardChanges(item) {
                // Set old value if item changed
            }
        }
    }
</script>

This setup generates dynamic inputs from an array of items. It is important to correctly manage the behavior of the action buttons based on changes made to each current item.

For instance, if a user modifies the title of the second item and clicks on the Discard changes button, how can we revert back to the original value?

In addition, how do we effectively disable or enable action buttons by comparing ch

Answer №1

I have recently implemented a new array called oldValues and adjusted the methods accordingly. I also recommend using v-model instead of :value

<div>
    <div v-for="(item, key) in items" :key="key">
        <div>
            <input type="text" v-model="item.title">
        </div>
        <div>
            <input type="text" v-model="item.description">
        </div>
        <div class="actions">
            <button type="button" @click="discardChanges(key)" :disabled="!itemChanged">Discard changes</button>
            <button type="button" @click="sendChanges(item, key)" :disabled="!itemChanged">Save</button>
        </div>
    </div>
</div>
<script type="text/javascript">
    export default {
        data() {
            return {
                itemChanged: false,
                oldValues: [
                    {
                        title: "Apple",
                        description: "The bigger company of the world"
                    },
                    {
                        title: "Amazon",
                        description: "The bigger online store of the USA"
                    },
                ],
                items: [
                    {
                        title: "Apple",
                        description: "The bigger company of the world"
                    },
                    {
                        title: "Amazon",
                        description: "The bigger online store of the USA"
                    },
                ]
            }
        },
        methods: {
            sendChanges(item) {
                // Proceed to update the item by sending an API request
              this.oldValues[key]=item;
            },
            discardChanges(item) {
                // Revert to the old value if the item has been modified
               this.items[key]=this.oldValues[key];
            }
        }
    }
</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

What is the best way to display compiled Transcluded HTML in Angular?

I am facing a challenge in trying to display customized HTML content using Angular directives for nesting divs multiple times. When I execute the code below, the transcluded tag is displayed correctly but the browser output shows the string text " ". I att ...

How can I use Vue.js @scroll to create a dynamic CSS property?

I am developing a vuejs component for my project and I am looking to implement a zoom functionality on scroll within a div, similar to Google Maps. <div @scroll="zoomOnScroll"> <Plotly :data="info" :layout="layout" :display-mode-bar="false"&g ...

I am unable to invoke this function: TypeError: this.fetchData is not a function

Whenever I try to execute this.fetchData();, I encounter the error "TypeError: this.fetchData is not a function". Initially, I suspected that the context of 'this' was lost so I attempted using bind and arrow functions without success. How can I ...

Ongoing state configuration in a React hook

My custom hook: export function useToken2() { const { data: session, status } = useSession(); const [token, setToken] = useState<string | null>(null); useEffect(() => { if (status === 'authenticated' && session?.accessToken) { ...

Determine the estimated download duration using the $http protocol

I am experiencing an issue with a function that calculates the time it takes to download a text file (3MB in size) from my server. While it works well for single requests, when I attempt to run multiple requests simultaneously, the time spent waiting for a ...

Determining the parameter type for the directive

How can you specify the types of parameters for the directive in AngularJS? Which type should be used for & binding? Refer to ngdoc or jsdoc for an example code. UPDATE: I am looking for answers to the following questions * @param {<< What sh ...

What is the difference in performance between using named functions versus anonymous functions in Node.js?

Currently, I am working on a Node.js app and was initially using anonymous functions for callbacks. However, after referring to the website callbackhell.com, I discovered that using named functions is considered best practice for coding. Despite switching ...

What are the best practices for implementing media queries in Next.js 13.4?

My media queries are not working in my next.js project. Here is what I have tried so far: I added my queries in "styles.module.css" and "global.css" and imported them in layout.js I included the viewport meta tag under a Head tag in layout.js This is how ...

SyntaxError: Unexpected symbol

I have an issue with the following code: let op = data.map(({usp-custom-90})=> usp-custom-90 ) When I run it, I encounter the following error: Uncaught SyntaxError: Unexpected token - I attempted to fix it by replacing the dash with –, but t ...

Saving a custom form to the database in Django: A step-by-step guide

As a new Django user, I am facing challenges when it comes to submitting form data to the database. In order to create dynamic forms, I have opted to use a form that is not based on a model in order to capture field information. Currently, I have commente ...

Issue with activation of onClick event in case/switch statement

Currently working on a JavaScript project to recreate the Fallout terminal game, with one of the main aspects being comparing words selected by the user to those chosen by the computer. The concept of this hacking game is reminiscent of the board game Mas ...

Develop a schema for an array of arrays in NodeJS using mongoose

Looking to establish a database schema for storing the following data: { name : "xyz", admin : "admin", expense : [ jan: [{expenseObject},{expenseObject}], feb: [[{expenseO ...

Controller encountering JSON null data

I am currently working on a feature that allows users to send multiple email/SMS messages by selecting checkboxes. However, I am facing an issue where the data is not being passed correctly from my JavaScript function to the action method - all the data sh ...

JavaScript can be used to extract a specific value from a SOAP response

In order to extract the Patient ID (PATAA000000040) from the SOAP response below using JavaScript and insert it into a Mirth destination, we need to target the value under the livingSubjectId tag. It's important to note that this tag may repeat, but w ...

Creating unique image control buttons for each image within a div using a combination of CSS and JavaScript

How can I create image control buttons, such as close, resize, and rotate, for each individual image when hovering over it? Each image is contained within a draggable div. I want to display an image control button next to each image. This button should on ...

Experiencing an unusual issue with grunt: The Gruntfile.js seems to be missing the 'flatten' method

Encountering an unusual error message while attempting to run grunt stated: TypeError: Object Gruntfile.js has no method 'flatten' Being a beginner with node.js, npm, and grunt, I believe my installation of node, npm, and grunt was done correctl ...

Bringing @angular/code into a directory that is not within an Angular project

Currently, I have an Angular 2 project folder with a separate service folder named "auth.service.ts" located outside of it. Within this service file, I am importing `Injectable` from `@angular/core`. However, due to the service being located outside of t ...

Issues with retrieving JSON data from Google Books API object

I've been working on retrieving data from the Google Books API and displaying the titles of the first 10 results on a web page. The site is successfully making the request, and I have a callback function that handles the results as shown below: funct ...

Go back in time with your file and craft a dynamic structure

This particular method has the ability to rewind a file, generate a dynamic array based on size provided, and then proceed to read in data which will populate the _data structure dynamic array. It should be noted that stream is passed by value in this inst ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...