Reputation: 1233
I have a method that makes an asynchronous call.
methods: {
getPercentCovered() {
this.getPercentageCompletedBySubject(1).then((percent) => {
return percent;
});
},
It calculates a percent from an value returned by an ajax request.
The issue I suppose is the delay
<progress-bar :percent="getPercentCovered()"></progress-bar>
The value is never passed in before the prop is rendered. Is there a work around?
Upvotes: 3
Views: 12106
Reputation: 6788
The issue is not the delay. The problem is that getPercentCovered()
doesn't ever return percent
: it actually returns undefined
. You cannot return
the result of an asynchronous operation: the most you could do in such a scenario is return the whole promise and handle it in the child.
This famous answer highlights the general problem of your code.
Now, regarding the Vue part of your question, there are several ways to handle this. I guess the most straightforward is to pass a prop to the child which gets updated when the getPercentageCompletedBySubject
resolves. I'm putting the call in the created()
lifecycle hook. Maybe you should move it to an event handler, that really depends on the real use case:
//script
data() {
return {
percent: '', //or maybe null or whatever empty value.
};
},
methods: {
getPercentCovered() {
this.getPercentageCompletedBySubject(1).then((percent) => {
this.percent = percent; //instead of return from a handler, which does nothing ,
// now we assign to this.percent
});
},
created(){
this.getPercentCovered();
}
//template
<progress-bar :percent="percent"></progress-bar>
Upvotes: 9