Invoking a function in a Vue.js child component once the parent function has finished execution

I am faced with a situation where I have a simple button that triggers two functions, one in the parent component and one in the child component:

<btn @click.native="() => {functionParent();
$refs.childComponent.functionChild()}">Call functions<btn>

Although I am aware that using arrow function for @click event is not considered best practice, I plan to address this issue later.

The current problem lies in the fact that functionParent() needs to be executed fully before functionChild() can begin. However, in my case, functionChild() starts running before functionParent() is complete - which is causing issues. How can I rectify this? My goal is to ensure that functionChild() is only called after functionParent() has finished executing. Any suggestions on how to achieve this?

Edit: (More details)

In the parent component:

<child-comp
:result-array="resultArray"
ref="childComponent"> 
</child-comp>

<script>
methods: {
  functionParent() {
    this.resultArray = "result"
  }
}
</script>

In the child component:

<script>
props: ['resultArray'],
methods: {
   functionChild() {
      if (this.resultArray == "result")
       {return "correct"} else {return "done before functionParent()"
      }
}
</script>

Edit2: I've tried moving

this.$refs.childComponent.functionChild()
to the end of functionParent(), but it doesn't seem to change the outcome. It appears that the call to the function in the child component is happening before the child component receives the updated resultArray.

Answer №1

To tackle this problem, consider implementing promises as they are well-suited for this issue.

Start by creating an onClick function within your component that will be triggered by your button.

Ensure that the functionParent returns a promise.

Subsequently, your onClick function should resemble the following structure:

function onClick () {
  functionParent().then( () => {
    functionChild()
  })
}

Your function parent implementation may look similar to this example:

functionParent () {
    return new Promise((resolve, reject) => {
    // perform necessary actions ...
    resolve()
  })
}

We hope this guidance proves useful in resolving your issue.

For further information on promises, please visit the following link:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

It is advised not to rely on timeouts as they do not guarantee the correct execution order of functions.

Answer №2

In case someone encounters a similar issue, here is a simple solution that I came up with thanks to the assistance of @Meet Zaveri:

Simply invoke the functionChild() within the functionParent() function with a slight time delay. For example:

functionParent() {
  this.resultArray = "result"
  setTimeout(() => {this.$refs.childComponent.functionChild();}, 100)
}

By doing this, Vue will have enough time to send the updated data to the child component's props.

I acknowledge that there may be more optimal solutions out there for this issue, but if you are stuck or unsure, this method is straightforward. If you have a better alternative, feel free to share it here!

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

How can Jasmine be utilized to test JavaScript code that relies on the presence of a jQuery template?

My usual method for incorporating jquery templates into my html files is like this: <script id="some-template" type="text/x-jquery-tmpl"> The actual template content goes here... along with some data: {data} </script> After setting up the t ...

How do I set custom edge colors for shapes in Three.js instead of only using wireframe:true?

Looking to create a unique 3d bar graph with custom-colored edges. Seeking ideas on how to achieve this effect. Here is the code for creating my shapes: var threeWidth = 400, threeHeight = 300; var viewAngle = 45, aspect = threeWidth / threeHeight, ...

Does sharing values between different pages happen when we are utilizing Nuxt alongside Vuex Store?

Is it possible to share values between different pages using Vuex Store? We attempted to do so, but encountered an issue. While State returned the correct value on the same page, it was not set on different pages. Are we missing something in our implement ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...

Opting for PHP over JSON in a jQuery live search code

Is it possible to modify my jQuery Google Instant style search script to pull content from a PHP script instead of using the BingAPI? Below is the current code being used: $(document).ready(function(){ $("#search").keyup(function(){ var searc ...

Issue finding a route based on dates

Hey everyone, I'm working on a feature where I need to fetch tasks made by a user within a specific date range provided by the user. However, I am facing some issues with getting the date and routing it. Here is the URL format that I am trying to work ...

Exploring Vue's data binding with both familiar and mysterious input values

How can I model an object in Vue that contains both known and unknown values? The quantity is unknown, but the type is known. I need to present user inputs for each type, where the user enters the quantity. How should I approach this? data() { retur ...

Unlock the full potential of custom authorization providers when integrating them with Supabse

Supabase user here looking to implement authorization with a third-party service that isn't on the supported list. Any suggestions on how to go about this? ...

Altering the input type of a cloned element in Internet Explorer results in the loss of the value

When I have checkbox inputs displayed in a modal with preset value attributes, upon clicking "OK", I clone them and change their input types to hidden, then append them to a div in the document body. However, when trying to retrieve their values using jQue ...

featherlight.js - Execute code when modal is triggered

Situation with HTML <div id="form-lightbox"> <div class="form"> <div id="ajaxreplace"> <script type="text/javascript"> jQuery(function() { jQuery.ajaxReplace({ //parame ...

I'm curious if it's possible to create a scrolling marquee on an SVG path with the use of HTML and CSS?

I am interested in creating a unique effect similar to what is showcased on this website or in the main menu of Colin McRae Rally 2.0. My goal is to generate a path and animate text along it, with the letters wrapping around to the start as they reach the ...

Place additional text above the export button within Highcharts

Presently, I'm utilizing the Highcharts API here and here to customize the export button for Highcharts. I am attempting to position an ellipsis inside the export button in order to adhere to certain style guidelines. However, due to the limitations o ...

Utilize an array with dynamic referencing

I am attempting to reference a single index out of 30 different indices based on the user's actions, and then utilize ng-repeat to iterate through each item in the index. Controller: $scope.meals = [ { title: 'Abs', url:"#/app/mworkout ...

Exploring the functionality of trading-vue library in a simple setup using vanilla HTML and Vue CDN

<html> <head> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a0c0f1f3a48544c544b48">[email protected]</a>/dist/vue.js"></script> ...

Using vue-multiselect to pass an array of objects from Vue to Laravel

Having an issue with the vue multiselect package. Normally, with a traditional <select> element in vue, you can loop through an array of objects using v-for and pass the value based on object.id. However, when using the <multiselect> instead, t ...

What is the best way to get rid of a connect-flash notification?

I'm having trouble removing the message (with the username displayed) after logging out by pressing the logout button. Every time I try to press the logout button, it just refreshes the page without any action. I want to stay on the same page and not ...

Vue-powered custom mute/unmute button malfunctions inexplicably when deployed, despite functioning flawlessly during development phase

I'm currently struggling to understand why the mute/unmute button is not functioning as expected. The issue seems to arise when the code is deployed on Netlify, as it works fine on localhost. Essentially, the button mutes and unmutes the video, but th ...

Creating various layouts in Ember.js allows for flexibility and customization in

Currently working on an emberjs project and aiming to incorporate two distinct layouts - one for the main application template and another for specific templates. I prefer not to have all views rendered within the application template, similar to how you ...

Tips for implementing X-XSS-Protection: 1; mode=block in HTML

I'm struggling with where to place this piece of code in my existing code. Should it be added to the header section? <head> <meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" /> <title> ...

What is the best approach to configure Nuxt.js to recognize both `/` and `/index.html` URLs?

Currently, I have set up my Nuxt.js in default mode with universal and history router configurations. After running nuxt generate, the generated website includes an index.html file in the dist folder. This means that when the website is published, it can ...