I have a property computed as follows:
private get ChangeGroup(): IResults[] {
Axios.get(process.env.VUE_APP_BASE_URI + 'results?GroupNumber='
+ this.selected,
{withCredentials: true})
.then(data => {
this.items = data.data;
let i = 1;
this.items.forEach(
(e: IResults) => {
e.position = i;
i++;
}
);
return this.items; <----- 2
})
.catch(error => {return []}); <--- 1
}
It's written that way, because the application uses typescript, so the function needs to return something.
On the line marked 1, it returns empty.
On 2, it returns full.
But of course, the problem is that this async call returns automatically. So how do you make this wait until the call actually comes back, and has something to return?
TL; DR;
You can't trivially. The computed properties are synchronous and are executed at the moment they are needed, because VUE caches them so that they do not have to be recomputed if the variables they contain are reactive.
Explanation and alternatives
There is the vue-async-computed component , which allows you to use asynchronous computed variables. However, this method is not compatible with typescript, since it involves passing its definition to typescript, which is explained in the VUE manual.
But it is not explained anywhere how to define in the vue object model a new internal declaration type.
Therefore, although such an object can be used without Ts, it is useless in this case.
The trivial solution is to use a watch, which controls the property that is being changed, and whose result is stored in another property, which can be changed asynchronously.
Evan explains in this thread that although this library is a good idea, and that it could even be added to the framework, but then they relapse into overextending the base, which always tries to be clean, and let the library evolve on its own. alone.
I added in a thread where the original author of the component is asked how to use this with Ts, a question to see if they had managed to include this in a VUE class component.
The solution at this moment, then, is as:
Where selected is the reactive variable that fires this event. In the example case (and here too) it is the variable that is used to make the request. For that matter, it's a selection change in a combo.