Vue: Ensure user-triggered changes are detected in form input

Hello everyone, I recently started using Vue and I'm trying to achieve the following goal.

I have a form with some data and a save button. Before the page fully loads, it needs to fetch data from the database and pre-fill the form. The save button should initially be disabled because all the data is already filled. Only when the user makes changes to the form, the save button should become enabled and allow the user to save the changes.

I understand that I should be using the watch property, but I'm not sure how to actually implement this. Any guidance would be greatly appreciated!

The structure of the form data looks like this:

data(){
  return {
     form: {
         firstName: "",
         lastName: ""
     }
  }
}

Answer №1

To achieve this functionality, you can utilize two separate objects named actual and modified.

In the code snippet provided, underscore js is utilized for deep clone or isEqual functionality, so ensure that you have imported it.

computed: {
// Use the 'isDataChanged' property to determine whether changes have been made
isDataChanged: function() {
    return _.isEqual(this.actualForm, this.modifiedForm);
 }
},
data() {
return {
    actualForm: {
        firstName: "",
       lastName: ""
    },
   modifiedForm: {
       firstName: "",
       lastName: ""
   }
 }
}, 
methods: {
fetchData: function() {
    // Retrieve data and assign it to the actual form
    this.actualForm = responseData;
    this.modifiedForm = _.cloneDeep(this.actualForm) // this will create a new instance
 }
}

Answer №2

If you want to monitor changes in a form, you can use the following code snippet. To watch properties nested within the form, you can set deep:true.

watch: {
    form: {
      deep: true,
      handler(val) {
        // Add functionality to enable save button. You may also check other conditions before enabling it.
      }
    }
  }

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 Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

VueJS appears to be failing to generate chunks for lazily loaded route components

One peculiar issue I am facing in my VueJS application is related to the router and the LoadingPage.vue component. The router configuration for this component looks like this: { path: "/loading", name: "loading", component: () =&g ...

Is it feasible to update just one key within an exported type using setState in TypeScript?

Recently, I decided to dive into Typescript within my React App and encountered an error that has left me stumped. I'm wondering if it's possible to access a specific key in an exported type and modify its value? Here is how I've exported ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...

The integration of numerous filters in the Google Maps API allows for complex intersection

After weeks of searching, I finally found a solution for filtering multiple criteria using JavaScript and the Google Maps API. The functionality I found is exactly what I need for my map, but I'm struggling to get it to work properly. Can someone help ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

What is the maximum number of JavaScript functions allowed in a single HTML file?

My HTML5 file includes JavaScript (created from CoffeeScript) directly within the HTML file, as I prefer this approach for my HTML/JavaScript programming. The code consists of four JavaScript functions that convert one temperature unit to another. Strang ...

Child component in VueJs is undergoing a situation where the variable is found to be

Whenever an event is triggered, a function is called to populate a variable and open a modal from a child component. However, in the modal, the new variable appears empty initially. If I close and then reopen the modal, the data finally loads. I have atte ...

Tips for optimizing my Vue.js code for search engine indexing

Recently, I created a section of a website using Vue.js (CDN version instead of CLI) that displays entries based on location. However, I discovered that the data is not able to be indexed since it loads in the front end. After researching, it seems like I ...

Pressing the submit button in the Material UI table clears all selected checkboxes

Take a look at this code snippet: https://jsfiddle.net/aewhatley/Lkuaeqdr/1/. My objective is to construct a table with a submit button utilizing Material-UI components. const { Table, TableHeader, TableHeaderColumn, TableBody, TableRow, Table ...

Add a parameter to the iframe that is dynamically loaded into the DOM after a user clicks on

I am attempting to automatically play a YouTube video within an iframe. The iframe is only loaded into the DOM when I activate a trigger element: a.colorbox.cboxElement How can I add the parameter ?autoplay=1 to the end of the iframe URL upon click, consi ...

Is it possible to extract content from a remote website by utilizing javascript and iframe?

Are there any resources available for working with iframes in Ruby on Rails? **UPDATE:** I have a link that directs to an external website. I am looking to extract the content from that site and save it within my application. Is this achievable without re ...

How can we format a number to match the Brazilian number system while still maintaining its ability to be used in calculations?

Is there a known method to convert the number 123,123,214.93 into Brazilian currency format (123.123.214,93) for display purposes only? I attempted to achieve this conversion using a JavaScript function where I added periods after every 3 numbers and repl ...

Utilizing Chart.js to extract and display specific data values from an external JSON file

I am currently engaged in a journey of self-exploration where I aim to create a chart depicting the number of anime shows with comedy or fantasy genres. The data for my chart will be sourced from an external JSON file (anime.json) on my computer. Initially ...

Tips for avoiding simultaneous state transitions in Angular UI Router

My situation in my Angular application involves a frustrating issue. Whenever a user double-clicks quickly on a link to a specific state (ui-sref link), the target state starts loading twice. This would be manageable if the state window didn't freeze ...

Timepicker.js - Incorrect Placement of Time Picker in Certain Scenarios

Utilizing the timepicker.js library to select a time, I am encountering an issue. When clicking on the input field, the timepicker should appear next to it. This function works as expected when the input is within the main view of the document. However, if ...

Transmit an array using a GET Request

I am currently working on a project where I need to make a GET request from JavaScript to Python and pass a 2D array. Here is an example of the array: [["one", "two"],["foo", "bar"]] However, I am facing issues with passing this array correctly. In my Ja ...

Sending a properly formatted string on Postman

My website allows users to answer coding problems. I am looking to store the questions and answers in a mongodb database. However, when testing the routes on my express application, I am encountering difficulties in sending formatted text in the request to ...

State in Vuex has been copied into a data object property, making it impossible to delete an item from the array

I have successfully copied the state from Vuex to an array in my component's data(). However, I encountered an issue when trying to remove the first item from the cloned array using shift(), and then add it back with unshift(). The error message displ ...

Creating a dynamic canvas with a three-dimensional model using three.js: A step-by-step guide

I'm currently developing a website where I have integrated a canvas element to display a 3D object (specifically, a cube) using three.js. The canvas is housed within a div, following the guidelines found in various documentation. The issue arises wh ...