I have button that executes 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 problem is that applyColor cannot execute properly because this.json.data
is not rendered until parse()
function ends.
I'd want to achieve something like this:
this.json.data = getDataFromAPI();
exit parse() method
execute applyColor();
but without huge changes to code -> maybe some kind of "put that aside for later" like
this.json.data = getDataFromAPI();
promise(500ms) applyColor();
exit parse() method
500ms
executes applyColor()
What I've been trying?
this.$forceUpdate(); before apply
You can use the computed properties to trigger an update based on the update of other properties: https://v2.vuejs.org/v2/guide/computed.html
But I don't fully understand why you loop through the elements of the dataset in the applyColor method and why you don't loop it in the Vue template with creating a CSS class for the style like this:
<div v-for="element, index in json.data" :key="index" class="bg-red">{{element}}</div>
you need something like this
getDataFromAPI should be promise, when data comes you send 'this' variable as a reference using self.
parse: function()
{
var self = this;
getDataFromAPI().then((data)=>{
self.json.data = data
self.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";
}
}
Async and await seems like it will work with the least changes of code. You need to define parse with async and this.json.data = await getDataFromApi()
, doing it this way , the code will execute in the exact order you have it on description, so applyColors will have this.json.data . Ref: https://javascript.info/async-await
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.