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

How to streamline a JSON array within ADF copy activity

Is there a way to flatten an array of complex JSONs with nested arrays in the copy activity? Despite checking forums and samples, I've tried several methods without success due to the complexity of my JSON structure. Here's the JSON data: { & ...

Is there a way to enable scanned data to be automatically inputted into a field without manual entry?

I am in the process of creating a user-friendly Android app for virtual inventory management. I want the application to streamline data input by automatically populating text fields upon scanning, eliminating the need for users to manually click on each fi ...

React Switch not displaying various pages correctly

After creating a new component to switch between pages on my React app, I encountered an issue where the HomePage renders correctly when entering the site, but clicking on navlinks does not work. Additionally, when trying to access the url /contacto, ins ...

Developing in Java Script with ENVDTE involves adding a new project to an existing solution and placing it in a designated sub-folder for organization purposes

Currently, I am working on developing a Visual Studio extension for a new C++ project template using Visual Studio 2010. The approach I am taking involves utilizing the .vsz template method and customizing the default.js code to suit my requirements. Withi ...

"Unfortunately, SimplyScroll isn't functioning properly on this particular page

What is the reason for simplyscroll not being able to handle this div with nested divs? EXTRA INFORMATION The scrolling functionality does not work. Clicking on the buttons doesn't trigger any scrolling. Changing the contents of the div to plain tex ...

Implementing anchor tags in VueJS Swiper

Regarding a VueJS 2.0 project using Swiper v8.3.2, there is an issue with a swiperSlide that resembles the following code: <template> <a :href="url" :title="title" >{{ title }}</a> </template> How ca ...

The Yeoman/Grunt-usemin is failing to update the index.html file even after adding new JavaScript code

As I work on developing a web app using Yeoman and the Angular generator on Windows 7, I go through the process of running 'yo angular' followed by 'grunt' to build the app for deployment. The index.html file in the dist folder gets upd ...

Encountering an issue with a Discord bot causing it to malfunction and deviate from its intended

Initially, everything appears to be functioning properly with the bot. When I execute the ?listen command, it responds correctly with bot is collecting messages now.... However, the ?stop command does not seem to have any effect. Furthermore, when I try th ...

JavaScript code to remove everything in a string after the last occurrence of a certain

I have been working on a JavaScript function to cut strings into 140 characters, ensuring that words are not broken in the process. Now, I also want the text to make more sense by checking for certain characters (like ., ,, :, ;) and if the string is bet ...

Increase the gap between the legend and the chart when utilizing charts.js

I'm currently working on a project using charts.js and running into a slight issue. The legend for my bar chart is overlapping with the values displayed. I've been attempting to troubleshoot this problem without much success so far, so I would g ...

What is the best way to style MUI's Button component with a link to appear like a standard button?

I have a Button that allows users to download a file with a specific filename. Here is the code I used: <Button color='primary' href=`/apiproxy/objects/${id}/subobjects` LinkComponent={React.forwardRef((props, ref) => <Link {...pro ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

Sending a div class as a parameter to a JavaScript function

Wondering if it's possible to pass a div's class into a JavaScript function. I'm using SquareSpace so adding an id to the div is not an option, but it works fine with divs that have ids. JQuery is already loaded. This is my current train of ...

Improving Vue Component on Navigation

I am facing an issue with my navbar where I have two versions. Version 1 features a white text color, while Version 2 has black text. The need for two versions arises due to some pages having a white background, hence the requirement for black text. Bot ...

Unable to avoid clicking on previous dates in v-calendar (Vuetify)

I recently set up a v-calendar following the guidance provided in the Vuetify documentation. However, I'm encountering an issue where I can't seem to disable the click event for past days. This prevents users from creating events on days that hav ...

What is the best way to attach a jQuery UI event handler to a button that has been dynamically generated?

Currently, I have a jquery ui modal dialog box form that inserts items into a table. A specific column in the table contains a button which serves as a link to edit the particular row. My goal is to attach an event handler to this button so that when a use ...

Use jQuery to permit only numeric characters and the symbol "-" to be entered into a textbox

I have been working on a JQuery script that only allows users to input numbers in a text field. However, I am now trying to modify the code to also allow users to enter "-" (hyphen), but so far it's not working as expected. If anyone can provide assis ...

Arrange the objects in the array in React based on their time and date of creation

As a newcomer to the world of React.js and Redux, I am faced with an array of objects structured like this: quizList = [ { createdDate : 1543314832505, id:5bfd1d90d4ed830001f589fc, name:'abc'}, { createdDate : 1543314152180, id:5bfd1ae8d4ed83000 ...

How can Ext JS 6.2 automatically expand the East panel when the West panel is triggered?

In my Ext JS v6.2 Grid application, I am faced with the task of ensuring that if the WestRegion panel is closed, the EastRegion panel should open automatically, and vice-versa. Being new to Ext JS, I initially attempted to achieve this using jQuery. Howeve ...

Tips for preventing redundant code in various functions using Vue.js

I am currently in the process of learning both Javascript and Vue.js, and I am facing a challenge with avoiding duplicated code in two functions using Vue.js. Specifically, I am struggling to figure out how to prevent duplication when resetting data with t ...