`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

Incorporating JavaScript and Alpine.js to Monitor and Log Changes in Input Range Values

I have developed a basic app that logs the input range value to the console when the range input changes. Interestingly, it works flawlessly when I slide the slider left and right with my cursor. However, when I programmatically change the value using Ja ...

Unable to access child props in parent event handler in React

Currently utilizing React for building a UI, the structure involves a parent component and a child component as shown below: // Child Component var ListItem = React.createClass({ render: function() { var link_details = ( <div> ...

Issue with floating navigation bar functionality when resizing the page

After much tinkering, I have managed to create a floating navigation bar for my website. Most of the time, it works perfectly fine, but there's an issue when the window size is adjusted in the floating mode. Take a look at the image below for referenc ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

Experiencing difficulties when uploading information to an API in a React JS application

Trying to Send Data via React to Contact Form API Having issues trying to send input data through the API when clicking submit button. The error encountered is that the API call should look like this Example Link However, it calls in a different way Diff ...

Validation in Laravel and Vue.js

When I receive validation errors from my Laravel api in json format, it looks like this: { "error": { "billabletime": [ "The billabletime field is required." ], "time": [ "time must be an integer." ] } } Now, I am trying t ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

generate code to automatically output the content of a website

I'm in the process of creating a program that automatically navigates to a website and prints a page. Unfortunately, I'm encountering difficulties in getting it to function properly. I've attempted using the selenium chrome driver, but with ...

Sending a page identifier through a menu

Being new to vue/nuxt, I encountered an issue when setting up the frontend for a headless CMS. I have defined two routes as follows: Pages -StandardPage ->_standardPage.vue -InfoPage ->_InfoPage.vue Both my _standardPage.vue and _infoPage.v ...

The language is being detected, but the translation feature is not functioning properly with i18n

I've configured the i18n middleware in my Express Node js server as follows: // server.js import i18nMiddleware from 'i18next-express-middleware'; import i18n from 'i18next'; import Backend from 'i18next-node-fs-backend'; ...

Vue.js renders components after the job is completed

Currently, I am dealing with a component that requires me to initiate a request using socket.io: <template> <h1>Please do not display until the socket responds</h1> </template> <script> export default { befor ...

The React Native application is working fine on the emulator but is encountering some issues when trying

While the app runs smoothly on an emulator through Android Studio, I encounter an error when trying to run it from the CLI. error Failed to install the app. Ensure that you have set up the Android development environment properly: <a href="https://fac ...

How can I retrieve the `checked` state of an input in Vue 3 using Typescript?

In my current project, I am using the latest version of Vue (Vue 3) and TypeScript 4.4. I am facing an issue where I need to retrieve the value of a checkbox without resorting to (event.target as any).checked. Are there any alternative methods in Vue tha ...

Having trouble displaying information in a table using React JS

I devised a feature to display one column of a table and one column for checkboxes (each row should have a checkbox). I stored this file in a component folder with the intention of creating a page where the user selects an account type, and then a new tabl ...

invoke a function upon successful completion of an ajax call in a datatable

Can we trigger a JavaScript function after a successful AJAX call in a datatable? Here is the code I am attempting to use: var dataTable = $('#app-config').dataTable( { "bAutoWidth": false, ...

Ways to transfer GET form information to Express?

I am working on a form that needs to pass parameters correctly <form action="./search" method="GET"> <div class="form-group text-center"> <input type="text" name="keyword" placeholder="Search Term" /> ...

Spring application encountering 404 error following nginx request

My Vue application is connected to two different backend services. One of them uses SpringBoot, which is currently not compatible with nginx. The configuration in my nginx.conf.template file includes: location /apcc { proxy_pass ${APCC_BACKEND_URL}; ...

An error occurred: TypeError - Unable to access the 'value' property of a null object during a value change

Example ImageCreating a dynamic form where rows and select box options are added dynamically using 'x' and 'i' increment values in two JavaScript functions. The code works fine when the option selected is 0.5, but throws an error Uncaug ...

What is the best way to incorporate a Vue3 Pinia store into the methods of a component?

I've been struggling to locate the solution to a straightforward query. While going through various demonstrations and guides for the Pinia store, I noticed that they all mention referencing the store in a component's setup before utilizing it wi ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...