How can I make a method in VueJS wait to execute until after rendering?

There is a button that triggers the parse method.

parse: function()
{
    this.json.data = getDataFromAPI();
    applyColor();
},
applyColor: function()
{
    for (var i=0; i<this.json.data.length; i++)
    {
        var doc = document.getElementById(this.json.data[i].id);
        doc.style.background = "red";
    }
}

The issue here is that applyColor does not execute properly because this.json.data is not available until the parse() function finishes.

I would like to achieve a flow similar to:

this.json.data = getDataFromAPI(); 
exit parse() method
execute applyColor();

without making major changes to the code. Perhaps something along the lines of "set that aside for later" such as:

this.json.data = getDataFromAPI(); 
promise(500ms) applyColor();
exit parse() method
500ms
executes applyColor()

What I have attempted so far?

this.$forceUpdate(); before apply

Answer №1

If you want to trigger an update based on the changes in other properties, using computed properties is a good option: Check out this link for more information

I'm curious about your approach of looping through the elements of the dataset in the applyColor method instead of creating a CSS class in the Vue template like this:

<div v-for="element, index in json.data" :key="index" class="bg-red">{{element}}</div>

Answer №2

Here is an example of how you can achieve this:

To ensure that getDataFromAPI returns a promise, make sure to send 'this' variable as a reference using the self keyword.

parse: function()
{
    var self = this;
    getDataFromAPI().then((data)=>{
     self.json.data = data
     self.applyStyle();
    })

},
applyStyle: function()
{
    for (var i=0; i<this.json.data.length; i++)
    {
        var element = document.getElementById(this.json.data[i].id);
        element.style.background = "red";
    }
}

Answer №3

Utilizing async and await appears to be a seamless solution with minimal code modifications required. By implementing async in the definition of parse, and using

this.json.data = await getDataFromApi()
, you can ensure that the code will execute in the specified order as outlined in the description. Consequently, applyColors will have access to this.json.data. For more information, please visit: https://javascript.info/async-await

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

repeating the identical content in the same setting

I am encountering an issue with jquery as I have 2 different sets of icons, each of which I want to do the same thing: My primary codes are <ul> <li> <a href=""> <i class="fa fa-facebook"></i> ...

How about rejuvenating a Div with some PHP magic inside?

My goal is to automatically update a div every x seconds by using the following code: The div only contains a small PHP timezone code. This is the code snippet I am implementing: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ li ...

Enhancing Tables with Angular for Dynamic Translation and Filtering

I'm facing a challenge with my search feature in a basic table - <table> <thead> <tr> <th> Name </th> <th> Lastname </th> <th> Job Title </th> </tr> </the ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...

Is there a way to locate a specific word within a sentence using JavaScript

I have these lists of answers: For example: const answerList = [{index: 2, answer: nice}, {index: 5, answer: sunday} ...] similar to that Also, I have a sentence: For instance: "hi i'm theo nice to meet you. how are you" My goal is to identify ...

Extract the last word from a string, filter out any special characters, and store it in an array

Here is the content of the xmlhttp.responseText: var Text = "FS2Crew A320 Checklist_1""FS2Crew Flight Crew A320 Main Ops Manual_1""FS2Crew Flight Crew A320 Main Ops Manual_10""FS2Crew Flight Crew A320 Main Ops Manual_11&q ...

What are the steps to successfully deploy a static website created with Next.js on Vercel?

Using the Next.js static site generator, I created a simple static site that I now want to deploy on Vercel. However, I keep encountering an error during the build process. While I have successfully deployed this site on other static hosting platforms befo ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

Tips for creating a custom axios response depending on the error code returned by the response

I am currently working on implementing a global error handling system in my Vue application. Within my project, I have an api.service.js file that contains the necessary code for Axios setup and various HTTP request functions such as get and post: /** * S ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

A guide on invoking a servlet using a jQuery $.ajax() call

I am having trouble calling a servlet using jQuery's .ajax() function. It seems like the servlet is not being called or parameters are not being passed to it. Despite searching extensively online, I have not been able to find a solution. Any suggesti ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Trouble connecting JavaScript to Node application for proper functionality

After setting up Node/Express/EJS, I am now trying to include js files, but my alert("working"); is not working as expected. Quite ironic, isn't it? The main objective is to load learnJs.js in the browser and trigger the alert so that I can confirm e ...

Is there a way to create an event listener that responds to a simultaneous click of both mouse buttons?

Despite my extensive research on the Internet, I was unable to find any examples. Interestingly, Vue only supports right and left clicks separately which I find peculiar as it seems like a basic task that can easily be accomplished with plain Javascript. ...

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

Arranging data in Ember: sorting an array based on several properties in different directions

Is it possible to sort a collection of Ember Models by multiple properties, where each property can be sorted in different directions? For example, sorting by property a in ascending order and by property b in descending order? Update I attempted to use ...

Hide the Modal Content using JavaScript initially, and only reveal it once the Onclick Button is activated. Upon clicking the button, the Modal should then be displayed to

While trying to complete this assignment, I initially attempted to search for JavaScript code that would work. Unfortunately, my first submission resulted in messing up the bootstrap code provided by the professors. They specifically requested us to use Ja ...

CSS guidelines for layering shapes and divs

Currently, I am in the process of developing a screenshot application to enhance my understanding of HTML, CSS, and Electron. One of the key features I have implemented is a toggleable overlay consisting of a 0.25 opacity transparent box that covers the en ...

The onBlur() method is not functioning properly in JavaScript

Created a table using PHP where data is fetched from a MySQL database. One of the fields in the table is editable, and an onBlur listener was set up to send the edited data back to the MySQL table. However, the onBlur function doesn't seem to work as ...

Bringing in a JavaScript file into a Svelte component

Today, I stumbled upon Svelte and I am really intrigued by the concept. However, I encountered an issue while attempting to import a small helper.js file. No matter what I try, whenever I reference the class, I receive the error: ReferenceError: Helper ...