Executing Code in VueJS after an Event has been Successfully Dispatched

I am currently facing an issue where the form in the child component is being cleared before the event containing the entered form data is successfully passed to the parent component. As a result, the event passes empty values to the parent. I have tried using a timeout to delay the clearing of the form with no success. Is there a way to ensure that the form is only cleared after the event completes and the data has been saved?

Here is the code snippet:

Child Component

<template>
    <!-- Contains a form -->
</template>

<script>
export default {
    
    data() {
        return {
            additionalInfo: 
                {
                    id: new Date().toISOString(),
                    fullName: '',
                    preAuthorize: '',
                    serviceAddress: ''
                },
            validation: {
                fullNameIsValid: true,
                serviceAddressIsValid: true
            },
            formIsValid: true,
            addServiceButtonText: '+ Add Service Notes (Optional)',
            serviceNotes: [],
            showServiceNotes: false,
            enteredServiceNote: '' //service notes addendum
        }
    },
    computed : {
        // something
    },
    methods: {
        
        setServiceNotes(){
            this.showServiceNotes = !this.showServiceNotes;
        },
        addAnotherParty(){
            this.validateForm();
            if(!this.formIsValid){
                return;
            }
            this.$emit('add-parties', this.additionalInfo); //event
            console.log(this.clearForm);
        },
        
        clearForm(){
            this.additionalInfo.fullName = '';
            this.additionalInfo.serviceAddress = '';
            this.additionalInfo.preAuthorize = false;
        }
    }
}
</script>

Parent Component

<template>
    <div>
        <base-card 
        ref="childComponent"
        @add-parties="updateAdditionalInfoList">
            <!-- Wrapper for the `Parties Being Served` component-->
                <template v-slot:title>
                    <slot></slot>
                </template>

        </base-card>
    </div>
    
</template>
<script>
export default {
    data() {
        return {
            hasElement: false,
            selectedComponent: 'base-card',
            additionalInfoList : [],
            clearForm: false
        }
    },
    methods: {
        updateAdditionalInfoList(additionalInfo){ //save changes passed via event
            this.additionalInfoList.push(additionalInfo);
            console.log('emitted');
            console.log(this.additionalInfoList);    
            setTimeout(() => {
                this.$refs.childComponent.clearForm();  //clear the form in child
            }, 2000);
            
        }
    }
}
</script>

Answer №1

Give this a try

addAnotherParty(){
  this.validateForm();
  if(!this.formIsValid){
    return;
  }
  let emitObj = JSON.parse(JSON.stringify(this.additionalInfo));
  this.$emit('add-parties', emitObj); //event
  console.log(this.clearForm);
}

In case your object is not deeply nested, you can opt for

let emitObj = Object.assign({}, this.additionalInfo);

as an alternative to stringifying and parsing.

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

Can images be sent to an Express API using SvelteKit's `on:change` event handler in combination with Form Actions?

I have a SvelteKit application that interacts with an Express API to store user data. Within my app, there is a form containing an input file field where users can upload images to be saved on the Express server using Form Actions. The issue I am facing ...

Error encountered in node.js script due to misuse of Sqlite's SQLITE_MISUSE functionality

Upon running my code with this query, I have encountered a situation where all tables are listed sometimes, while other times only one table is shown and consistently the following error is displayed: Query Error: Error: SQLITE_MISUSE: unknown error I ha ...

What's the issue with my virtual array not functioning?

Check out this example I created: http://jsfiddle.net/stephane_klein/Cgn2c/1/ I am attempting to create a "virtual" array in the "App.my_list2". Unfortunately, my code is not working as expected. Can you help me troubleshoot and fix the issue? Thank you ...

Approach for checking duplicates or empty input fields through PHP, AJAX, and JavaScript

Looking for a solution to validate and check for duplicate values when listing, creating, or deleting products using a REST API. I tried using rowCount in the php file to check for duplicates but I feel there might be a better approach that I am missing. N ...

Unable to delete data in Laravel 8

I am new to Laravel and facing an issue when trying to delete a row with a modal. The problem is that only the first row is getting removed and I can't figure out the reason. Here is my modal setup: <p class="card-text"><small clas ...

How can I execute a task following a callback function in node.js?

Is there a way to run console.log only after the callback function has finished executing? var convertFile = require('convert-file'); var source, options; source = 'Document.pdf'; options = '-f pdf -t txt -o ./Text.txt'; ca ...

MongoDB results are being pushed into an array, yet the array continues to stay devoid of any data

Hello all! This is my introductory question on stack overflow, so I appreciate your patience. I am currently working on a controller function that is responsible for rendering the Google Maps API. My goal is to iterate through the results fetched from Mon ...

Tips on customizing Char.js doughnut charts

How can I make the doughnut thinner while keeping it thicker? What adjustments should be made? I attempted to implement changes and it worked successfully, but now I need to adjust the width. How can I do this? TS File. import { Component, OnInit } from ...

Ways to switch the class of the nearest element

When an image within the .process class is clicked, I am using the following code to toggle the class of .process-info to .process--shown. The code successfully toggles the class; however, it affects all elements on the page with the class of .process-inf ...

Restricting Meteor Publish to specific user (admin) for all collections

Is there a method to exclusively publish all meteor collections to users with the role of {role: "admin"}? The meteor autopublish package grants database access to all clients. Are there any techniques to utilize the autopublish package while implementing ...

Encounter a 401 error code while attempting to fetch data from CouchDB using an AJAX request

I attempted to make an AJAX call in a JavaScript file to fetch data from CouchDB. Unfortunately, I encountered a 401 error message: Failed to load resource: the server responded with a status of 401 (Unauthorized) This is an extract of my JavaScript cod ...

Encountering unexpected fetch requests to JSON files when using getStaticProps/getStaticPaths

My webpage seems to be functioning correctly, however I have noticed that in the console there are 5, 404 errors appearing on fetch requests. It's puzzling where these errors are originating from. Interestingly, these 404 errors only occur in the pro ...

Switching <div></div> to inline-block doesn't seem to have any effect (repl.it provided)

Could someone assist me with changing the div element to an inline block? I've been having trouble with it. For reference, here is my repl.it: https://repl.it/repls/AwareContentTechnician ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Safari is struggling with the backface visibility feature not functioning as expected

I have implemented a cssflip animation in my code where the element rotates on hover. I included transition and backface-visibilty properties. While it works well on Chrome, I faced issues with Safari. I even added the webkit prefix for Safari browser. `. ...

Challenges with Expanse in Object-Oriented JavaScript

I'm currently working on incorporating objects from a JSON file into an array within my JavaScript object using the $.getJSON() function in jQuery. However, I've encountered scope challenges where the array elements appear to be defined inside th ...

What are the differences between a Django/React app API when in production versus during development?

Recently, I created a React app that relies on Axios for fetching APIs. During the development phase, I noticed an issue with the API URL configuration. Since my ReactApp was hosted on localhost:3000 but making API calls to 127.0.0.1 - I encountered some e ...

Preventing the use of the <select> tag in JavaScript

As a beginner in JavaScript, I thought it would be a great idea to work on a simple Calculator project. I've already tackled the basics like addition and subtraction, but now I'm contemplating adding a squareroot function to it. The design incl ...

Using JavaScript to dynamically invoke a function and pass parameters dynamically

Exploring a dynamic method call with parameters in JavaScript. let obj = { method: 'foo1', params: ['one', 'two'] } foo1(p1, p2) { // do something } To execute it => [obj.method](obj.params) Is there a way to dyn ...

Node.js tip: track down and address ignored errors in your code

Is there a method in node.js to track and log all exceptions? I find process.on('uncaughtException') insufficient for my needs, as I want to log all handled and unhandled exceptions, even if they were caught and disregarded using a catch block s ...