Trigger an event, pause, and subsequently trigger another one within Vue

I have successfully emitted the following events to the parent component:

this.$emit('sendToParent1', true);
this.$emit('sendToParent2');
this.$emit('sendToParent3');
this.$emit('sendToParent4', true);
this.$emit('sendToParent5', false);

However, I encountered a specific issue that requires me to emit these 5 events in sequence, one after another.

//emit this first and wait for parent to finish its task
this.$emit('sendToParent1');
//after parent finishes, emit next event from the child
this.$emit('sendToParent2');
//same pattern for emitting the next event after parent completes processing
this.$emit('sendToParent3');
//repeat for next event
this.$emit('sendToParent4', true);
//and again for the last event
this.$emit('sendToParent5', false);

I believe the best solution is to use a prop to detect when an event has completed its task and then signal the child component to proceed with the next emission. Can anyone provide guidance on how to implement this?

The Parent component includes the following:

<component v-on:sendToParent5="parentFunctionFive" v-on:sendToParent4="parentFunctionFour" v-on:sendToParent1="parentFunctionOne" v-on:sendToParent2="parentFunctionTwo" v-on:sendToParent3="parentFunctionThree"></component>

The Parent component contains the following methods:

         parentFunctionOne: function() {
                axios.get('/api/do_something-1/')
                .then((res)=>{
                    this.something1 = res.data;
                })
                .catch((error)=>{
                    console.log(error);
                });
            },

         parentFunctionTwo: function() {
                axios.get('/api/do_something-2/')
                .then((res)=>{
                    this.something2 = res.data;
                })
                .catch((error)=>{
                    console.log(error);
                });
            },

           parentFunctionThree: function() {
                axios.get('/api/do_something-3/')
                .then((res)=>{
                    this.something3 = res.data;
                })
                .catch((error)=>{
                    console.log(error);
                });
            },

       parentFunctionFour: function(passed_value) {
            //updating a variable in data with the passed value
            this.trueOrFalse = passed_value;
        },
        parentFunctionFive: function(passed_value) {
             //updating a variable in data with the passed value
            this.valuePassed = passed_value;
        }

Answer №1

To provide a more accurate response, it would be helpful if you clarify your end goal (refer to the XY problem), but based on the information presented, I suggest passing a function named next as the event parameter and triggering it upon completion of a task to progress to the next stage.

this.$emit('sendToParent1', {
 value: true,
 next: 
  () => this.$emit('sendToParent2', {
       value: false,
       next: () => this.$emit('sendToParent3', false);
     })
});
parentFunctionOne: function({value, next}) {
  axios.get('/api/do_something-1/')
    .then((res)=>{
        this.something1 = res.data;
        next() // proceed
    })
    .catch((error)=>{
        console.log(error);
    });
},

parentFunctionTwo: function({value, next}) {
  axios.get('/api/do_something-2/')
    .then((res)=>{
        this.something2 = res.data;
        next() // proceed
    })
    .catch((error)=>{
        console.log(error);
    });
},

parentFunctionThree: function() {
  axios.get('/api/do_something-3/')
    .then((res)=>{
        this.something3 = res.data;
    })
    .catch((error)=>{
        console.log(error);
    });
},

Answer №2

Consider revisiting your implementation strategy for the component. One suggestion is to emit a single event containing all necessary information, then have the parent call the appropriate function.

To facilitate this approach, you could use a variable that is sent with the event and increment it each time an event occurs. In the parent component, track this variable and execute events in the correct order, similar to how it's done in the HTTP protocol.

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

Tips for aligning an element vertically when it has a float using CSS or JavaScript

I am struggling with centering the image within the article list loop I created. The code snippet looks like this: <article class="article <?php if($i%2==0) { echo 'even'; } else { echo 'odd'; } ?>"> <section class ...

Error: The server instance pool has been terminated, requiring enhancements to the existing solution

I'm facing an issue where removing the client.close() seems to solve the problem, but I can't leave connections open to the database after the function is done. It doesn't feel secure to me. Even though the initial write completes successful ...

The concept of matryoshka logic applied to data manipulation

"mainData"{ entities:[] }, "data2":{ entities:[ { name:"mainData": //entites }, { name:"mainData": //entites }, { name:"m ...

Refresh the block's content seamlessly without the need for a page reload

Within the index.html page There exists a block called content that contains various content blocks. An additional navigation menu with numerous links is present. It is important that when you click on a menu link, the content within the content block re ...

Utilizing JavaScript to Parse RSS XML Feeds Across Domains

Looking to parse an RSS (XML) file without relying on the Google RSS feed. I have attempted using JSONP, but it resulted in downloading the file and throwing an error "Uncaught SyntaxError: Unexpected token < ". $.ajax({ type: "GET", ur ...

Make a copy of an array and modify the original in a different way

Apologies for my poor English, I will do my best to be clear. :) I am working with a 3-dimensional array which is basically an array of 2-dimensional arrays. My task is to take one of these 2-dimensional arrays and rotate it 90° counterclockwise. Here is ...

Tips on showing an api call response in Reactjs

I am a beginner in Reactjs and currently working with nextjs. I have been trying to integrate a "newsletter" feature into my project. I have created a component for this which is functioning properly. However, I am facing an issue with displaying the "succ ...

Is there a way to dynamically update the text of $ionicPopup's subTitle in Ionic?

I am currently attempting to modify both the value and style of the subText attribute linked to an $ionicPopup within my app. Despite searching extensively, I have been unable to uncover a viable method for accomplishing this task. Is there a way to achi ...

An automated feature that smoothly transitions a large image onto the screen

I came across a plugin, possibly a slideshow plugin, that smoothly slides a large image along the y-axis. It's hard to explain, but imagine the visible image is only 600px by 300px, while the actual image is 600px by 600px. This plugin would scroll t ...

Is there a way to gradually reveal an element as I scroll to a specific position?

If the window top position is about 100px from the bottom, I want to create a fading in/out effect for the element overlay. Check out this image Any ideas on how to achieve this? .section-card{ position: relative; height: 500px; line-heigh ...

Generate JSON on-the-fly with ever-changing keys and values

I am new to coding and I'm attempting to generate JSON data from extracting information from HTML input fields. Can anyone guide me on how to create and access JSON data in the format shown below? { Brazilians**{ John**{ old: 18 } ...

The CSS style of the Div element is not being displayed properly when embedded with JavaScript

Currently, I am working on a simple page for practice purposes. The main issue I am facing is with a div element that has a red border and a blue background. Inside the div, there is a script tag calling an external JavaScript file. Surprisingly, the JavaS ...

Converting a JSON list into a JavaScript object for the purpose of creating a dynamic

Understanding how JSON's lists work when parsed as JavaScript objects is challenging for me. I am not very familiar with JavaScript, so there may be mistakes in my question and the proposed solution. Currently, I have a JSON file that needs to be conv ...

AngularJS Form Validation Error Handling

I am in the process of implementing Form Validation using AngularJS, and I have come across a scenario involving ng-class that is confusing me. Could someone please explain why they are utilizing ng-class in this manner? The presence of a map and an arra ...

Tips for showing the database list based on the chosen value in the drop-down menu

manage_bank Hey there, I need some assistance with displaying the bank name based on the selected dropdown option. For instance, if we choose 50 records, it should display 50 records of the bank name from the database. Additionally, I want the selected v ...

Tips on passing a JSON object from JavaScript to ASP.NET

I attempted to invoke a method in an asp.net controller using a json string/object from javascript. The asp.net controller code is as follows: public class HomeController : Controller { public ActionResult doWork(string data) { // dowork. ...

Guide on implementing a live media stream using JavaScript

I am looking to set up a live audio stream from one device to a node server, which can then distribute that live feed to multiple front ends. After thorough research, I have hit a roadblock and hope someone out there can provide guidance. I have successf ...

Execute an HTTP POST request to the Node server, sending an empty object

For my project, I am attempting to send an HTTP Post request to my Node server from an html form. Despite using Body Parser and setting it up correctly, I am facing an issue where the req.body on my server is returning as an empty object. Can anyone prov ...

Organizing elements in a javascript array by their attributes using AngularJS

Picture this scenario: a collection of different wines: [ { "name":"wine A", "category":[ "red", "merlot" ] }, { "name":"wine B", "category":[ "white", "chardonnay" ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...