`Check out Vue3's property watching feature`

Currently, I have a form that is being edited and the created method is used to prefill the form information from an api call, which works perfectly fine.

However, my goal is to monitor the fields in the form. If any of them are edited, I want to set a variable called "isFormEdited" to true.

This is how I have it set up:


watch: {
  'form': {
    handler: function(v) {
      console.log('form changed');
      // Here is where I would set the "isFormEdited" variable to be true.
    },
    deep: true
  },

The issue I am facing is that the console log occurs immediately upon page load because the form starts empty and then the created function fills the values with the api call data.

How can I work around this so that the "isFormEdited" value is only set to true when the form is actually manually changed?


created() {
      const getForm = axios.get(`api/dashboard/form/${this.$route.params.id}/edit`);
      const getFormTypes = axios.get('api/dashboard/form/types');

      axios.all([getForm, getFormTypes])
          .then(
              axios.spread((...responses) => {
                  this.form = responses[0].data;

                  if(!this.form.type_id) {
                    this.form.type_id = "";
                  }

                  this.form.fields.map((field) => {
                     if(field.options){ field.options = JSON.parse(field.options); }
                     if(field.mime_types_allowed){  field.mime_types_allowed = JSON.parse(field.mime_types_allowed); }
                     return field;
                  });

                  this.types = responses[1].data.data;
              })
          )
          .catch(errors => {
              alert("Error");
              console.log(errors);
      });

Thank you very much for your help.

Answer №1

To ensure your form is properly populated before setting isFormEdited to true, consider creating a new variable called dataLoaded. By default, set dataLoaded to false and update it to true only after populating your form. Then, in the watch handler, you can check if both dataLoaded and the form have been loaded before changing isFormEdited.

Here's an example implementation:

export default {
    data() {
        return {
            dataLoaded: false,
            isFormEdited: false,
        };
    },
    created() {
        const getForm = axios.get(`api/dashboard/form/${this.$route.params.id}/edit`);
        const getFormTypes = axios.get('api/dashboard/form/types');

        axios
            .all([getForm, getFormTypes])
            .then(
                axios.spread((...responses) => {
                    this.form = responses[0].data;

                    if (!this.form.type_id) this.form.type_id = '';

                    this.form.fields.map((field) => {
                        if (field.options) {
                            field.options = JSON.parse(field.options);
                        }
                        if (field.mime_types_allowed) {
                            field.mime_types_allowed = JSON.parse(field.mime_types_allowed);
                        }
                        return field;
                    });

                    this.types = responses[1].data.data;

                    this.dataLoaded = true;
                })
            )
            .catch((errors) => {
                alert('Error');
                console.log(errors);
            });
    },
    watch: {
        form: {
            handler: function (v) {
                if (this.dataLoaded) {
                    console.log('Form changed!');
                    this.isFormEdited = true;
                }
            },
            deep: true,
        },
    },
};

If the above approach doesn't fit your needs, you can also utilize Vue's instance method $watch to monitor changes in a specific data element at any point within your component.

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

Incorporate a personalized style into the wysihtml5 text editor

Is there a way for me to insert a button that applies a custom class of my choice? I haven't been able to find this feature in the documentation, even though it's a commonly requested one. Here's an example of what I'm looking for: If ...

Switching Json to Typescript

I have a file named items.ts with the following interface: export interface item{ Name: string; IsSystemItem: string; ConfiguredSegments: ConfiguredSegments; } export interface ConfiguredSegments { LiveA: LiveA; } export interface LiveA { Weig ...

Crafting personalized objects from an array

In the process of creating an object from an array, I am faced with a dilemma. The elements in the array are as follows: var arr = [ 'find({ qty: { $lt: 20 } } )', 'limit(5)', 'skip(0)' ] Despite my efforts, my code is ...

Which method is more appropriate for my request - GET or POST? Or should I consider

Recently, I've been exploring the world of get and post methods and could use some guidance! Within my App.js file, there is a user text input field and a submit button. I have a couple of tasks in mind for handling this information: Retrieve a str ...

The controller failed to return a value when utilizing the factory

I am attempting to pass a value from my view to the controller using a function within the ng-click directive. I want to then use this value to send it to my factory, which will retrieve data from a REST API link. However, the value I am sending is not ret ...

AngularJS - Leveraging the power of two-way data binding with JSON strings

I am a beginner with AngularJS and I'm currently working on retrieving, parsing, and displaying data from a SOAP web service. So far, I have been able to successfully make calls to a public weather service, capture and display the XML data that is ret ...

Capture data from ajax effectively by extracting and executing manipulations seamlessly

I have a project where I need to retrieve images from a database using Ajax and display them using a carousel plugin. This is the process: An image URL is saved to the database by an admin The frontend script makes an Ajax call to a PHP file and retrieve ...

Failed jQuery AJAX request to database with no returned information

I'm really confused about where the issue lies :S The button triggers a function that passes the parameter "sex" and initiates an ajax call to ajax.php, where I execute a MySQL query to retrieve the results and populate different input boxes. When I ...

Showing a loading animation inside an HTML element

I have a main webpage that contains several buttons. Each button, when clicked, loads a specific target page as an object within a div on the main page. The "target" refers to the page that will be displayed within the object. <script> .... chec ...

Any recommendations for building HTML in an iOS UIWebView?

When using a UIWeb view, how can I create HTML content? For example, I have some header html code. Then, I would like to include a JavaScript script and pass data to it. Once the JavaScript is injected, I want to add the remaining HTML content from a .html ...

`user implemented object comparison within a set in unity (es6)`

I am facing an issue where I need to handle multiple values and ensure that only unique ones are used. With the use of node js and access to harmony collections through the --harmony flag, I have considered using a Set as a potential solution. What I am s ...

Vue project encountering issue with displayed image being bound

I am facing an issue with a component that is supposed to display an image: <template> <div> <img :src="image" /> </div> </template> <script> export default { name: 'MyComponent', ...

The timestamp is currently displaying as 2014-11-02T05:00:00.000Z rather than the expected 2014-11-02 00:00:00

Issue: The SELECT * query is returning dates in the wrong format. I am using the mysql2 module to run connection.query() and pass data to a server-side variable, then accessing it on the client-side with AJAX. router.post('/applicants', functi ...

Invoke ajax to reset session once user navigates away from page

I am looking for a solution to automatically clear the PHP session array every time a user exits my webpage. However, I need to exclude cases where the user clicks on links with query strings. I attempted using Javascript code, but it did not work as expec ...

Oops! An uncaught exception error occurred because the primordials were not defined

I used npm to install the package called aws-s3-zipper, but now I am encountering an error. This is the code snippet causing the issue: AWS = require("aws-sdk"); var S3Zipper = require("aws-s3-zipper"); function zipFolderOnS3() { var zipper = new S3 ...

Launching a modal using a method in Vue.js that includes constantly changing content

I am currently developing a feature in my VueJs component that involves opening a modal when a certain condition becomes true, and then retrieving data from a controller to display in the modal. After searching online, I have not been able to find clear i ...

What are the implications of an unidentified callback function with parameters?

Check out this snippet: const fs = require('fs'); fs.readFile('foo.txt', 'utf8', (error, data) => { if (error) { throw new Error(error); } console.log(data); }); Can you figure out where the anonymous callback is recei ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

Tips for incorporating animation when opening a Jquery SimpleModal

The SimpleModal website features an animation-enabled example with the following sequence: 1. Display modal only 2. Fade in the overlay The code snippet for this animation is as follows: $("#the-div").modal({ onOpen: function (dialog) { dialog.overl ...

What is the AngularJS equivalent of prevAll() and nextAll() functions in jQuery?

Currently, I am working on a project that involves AngularJS and I'm having trouble finding an example that fits my needs... With AngularJS, I know how to apply a class when an element is clicked, but how can I add a class to all previous items and r ...