Issue with VueJS event emission not functioning properly after dispatching to the store

In my VueJS project, I have a parent component that contains a modal for submitting data. Once the data is submitted, the modal should automatically close and display the results on the parent page.

Inside the modal, there is a form that, when submitted, dispatches a store action and emits an event.

If I emit the event before dispatching the action, everything works as expected. However, if I do it inside the promise's then block, nothing happens.

Parent Component

Template

<template>
<div>
    <div v-if="this.status !== 'loading'">
        [...]
        <v-dialog 
            v-model="modalAgregarCuenta"
            fullscreen
            hide-overlay
            transition="dialog-bottom-transition">
            <modal-agregar-cuenta 
                ref="modalAgregarCuenta"
                @closeModal="modalAgregarCuenta = false">
            </modal-agregar-cuenta>
        </v-dialog>
        [...]
    </div>
    [...]
</div>

Script

<script>
import ModalAgregarCuenta from './ModalAgregarCuentaBancaria';
[...]

export default {
    components: {
        'modal-agregar-cuenta': ModalAgregarCuenta,
        [...]
    },
    data() {
        return {
            modalAgregarCuenta: false,
            [...]
        }
    },
    watch: {
        [...]
        modalAgregarCuenta(){
            if( this.modalAgregarCuenta )
                this.$store.dispatch(TRACKER_EVENT, { "vm": this, "eventName": 'modal-bank-add-open'});
            else
                this.$store.dispatch(TRACKER_EVENT, { "vm": this, "eventName": 'modal-bank-add-close'});
        }
        [...]
    }
    [...]
}

Child Component

Template

<template>
<v-card>
    [...]
    <v-container>
        <v-form ref="formulario" v-model="validation" @submit.prevent="submitForm">
            [...]
        </v-form>
    </v-container>
</v-card>

Script

<script>
    [...]
    methods: {
        submitForm(){
            console.log(this); //<-- Second image
            //this.$emit('closeModal'); //<-- This line works properly

            if(!this.$refs.formulario.validate())
                return;

            this.$store.dispatch(BANK_CREATE_REQUEST, {
                cbu: this.cbu,
                legalNumber: this.accountInformation.legal_number
            })
            .then((res) => {
                this.$emit('closeModal'); //<-- This line does not
                console.log(this); //<-- Third image
                //this.closeModal();
                //this.clear();
                //this.closeModal();
                //this.$emit('closeModal');
                //this.$emit('closeModal');
                /*setTimeout(()=>{
                    //$this.closeModal();
                    this.$emit('closeModal');
                }, 2000);*/
            })
            .catch(err => err);
        },
        closeModal(){
            this.$emit('closeModal');
        },
        clear(){
            this.cbu = '';
            this.legalNumber = '';
        }
    }
    [...]
</script>

Upon checking Vue Devtools, it appears that the event is emitted correctly, as shown in the following image:

https://i.sstatic.net/sNu3g.jpg

I also observed a strange behavior when using the "console.log" function with "this" before and after dispatching. It seems that while the same component is logged in the console, some properties have different values:

Before

https://i.sstatic.net/XxO7K.jpg

After

https://i.sstatic.net/nYVcU.jpg

UPDATE

[BANK_CREATE_REQUEST]: ({commit}, {cbu, legalNumber}) => {
        commit(BANK_CREATE_REQUEST);
        commit(UI_LOADING, true);
        return apiCall.post(WE_API + '/v3/bank', {
            cbu: cbu,
            legal_number: legalNumber,
            legal_type: null
        })
        .then(res => {
            commit(BANK_CREATE_SUCCESS, res);
            commit(UI_LOADING, false);
            return res;
        })
        .catch(err => {
            commit(BANK_CREATE_ERROR);
            commit(UI_LOADING, false);
            throw err;
        })
    }
    
[BANK_CREATE_REQUEST]: (state) => {
    state.status = 'loading';
},
[BANK_CREATE_SUCCESS]: (state, payload) => {
    state.banks.push(payload.data.model);
    state.status = 'success';
},
[BANK_CREATE_ERROR]: (state) => {
    state.status = 'error';
},

Any assistance on this issue would be greatly appreciated.

Thank you.

Answer №1

Make sure to verify the content of "this" - I believe you'll be disappointed by what you find inside the promise.

Here's a suggestion that might assist you:

let tempThis = this;
...
.then((res) => {
            tempThis.$emit('closeModal'); //<-- This line is functional now

Remember, you could also utilize async/await (ES6) in this scenario, eliminating this "issue". However, you'd need to monitor the response status yourself, so it may not necessarily result in clearer code or simplification.

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

What is the best way to integrate Vue application server with Express?

I'm currently using a Vue app that is accessible at http://localhost:8080/ (using Vue CLI), and my backend is operating on Express at http://localhost:7070. I'm curious if there is a way to integrate both the frontend and backend under the same a ...

Refreshing the dat.gui variable is like giving it a fresh

In the dat.gui interface, there is a dropdown list that allows users to select a number. Once a number is chosen, the jumpSwitcher will correspond to that number. The goal is to replace each list with items specific to the number chosen for Starsystem. ht ...

Creating an array inside a Vue function

Currently, I am facing a challenge with restructuring an array in Vue.js. I am able to log the values within my method and push them into an array, but I'm struggling to format the array as required. The desired structure of the array should be like ...

Unexpected quirks noticed in the .html() function with jQuery and JavaScript

I have this straightforward HTML code: <td id="comment_td"> </td>. Notice the two spaces inside the td tags. I am checking the content of the td element like this: if (!$('#comment_td').html()) { $('#comment_td').html( ...

Using Vue SPA to bind single file components with Stripe Elements

Attempting to integrate Stripe Elements into a Vue SPA single file component has presented me with a challenge in the form of this error: IntegrationError: Missing argument. Make sure to call mount() with a valid DOM element or selector. at new t (http ...

Different ways to call an ES6 class that is bundled in the <script> tag

Currently, I am utilizing Webpack to transpile my ES6 classes. Within the bundle, there is a Service class that can be imported by other bundled scripts. class Service { constructor() { // } someMethod(data) { // } } expo ...

When the mouse is clicked, display the date field; and when a date is chosen,

I have a date displayed as plain text. When I click the 'change' button, a datepicker should appear below it. After selecting a date, the datepicker should be hidden and the date in the plain text should be updated accordingly. <span id="disp ...

How can I effectively remove event listeners while still preserving the context in a stimulus controller that listens to events multiple times?

My HTML page has the following controller setup: ... <div data-controller="parent"> <div data-target="parent.myDiv"> <div data-controller="child"> <span data-target="child.mySp ...

Is there a method for enabling GPT-3's "davinci" to engage in conversation with users via a bot on Discord by utilizing discord.js?

var collector = new MessageCollector(message.channel, filter, { max: 10, time: 60000, }) start_sequence = "\nAI: " retart_sequence = "\nHuman: " collector.on("collect", (msg) => { ...

Having trouble getting an HTML form to function with Ajax and PHP?

Seeking assistance from anyone who can lend a hand. I am delving into the complexities of Ajax, and I'm encountering issues where it seems like the script is being completely ignored or perhaps I'm just making a rookie mistake. Prior to display ...

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

Variable Returned by AJAX

I am attempting to send a variable using a select box via POST method, then use AJAX to submit the data and finally leverage that variable on the original page to update SQL queries. Below is the code snippet I currently have: <script type="text/j ...

Executing a JavaScript function through C# code

Does anyone have a code snippet for calling a JavaScript function from C#? Here's the scenario: I have an ASP.NET page with an ASP button. When this button is clicked, I want to call a JavaScript function. For example: In my ASP.NET page, <but ...

Despite the use of v-if and v-else directives in Vue 2, a specific component properties are not being updated while the others are updating

Vue2 is not updating one specific component (<Button>) inside v-if and v-else, while the rest of the content is updated. I have recently discovered a solution to make this code function, but I am still unsure about Vue2 re-rendering behavior. I worr ...

Tips for eliminating confidential content from adjacent/preceding entries in WordPress?

I recently incorporated a Vue.js single page application into a WordPress theme at wue-theme.app, and I am looking to implement next/previous navigation links for blog posts within the single-post template. However, I am facing challenges in excluding pr ...

Tips for modifying navbar appearance as user scrolls?

I am currently working on a website using Bootstrap 4. The goal is to create a navbar with a transparent background that transitions to white smoothly when the user scrolls down. I want the navbar to return to its initial state when the user scrolls back u ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

What are the steps to integrate and utilize DefinePlugin within your webpack configuration?

Hello, I'm currently trying to implement the DefinePlugin in order to update the version number and ensure that my JavaScript refreshes after a new build is released. Unfortunately, I am encountering issues with getting DefinePlugin to work properly. ...

Guide on using jQuery to dynamically update a section of an ejs template following an AJAX request in ExpressJS

I'm currently struggling to figure out how to dynamically update a portion of the DOM using EJS after a jQuery ajax call. The issue arises with a live search feature that successfully sends a request to the server, searches the database, and returns a ...

Update a section of my PHP webpage using setInterval()

How can I refresh a PHP value every second using setInterval()? I am familiar with refreshing values in HTML, but now I want to do the same with PHP values. Here is my code: <script> setInterval(function() { <?php $urlMachineOnline = ' ...