<script lang="ts">
import { createComponent } from "@vue/composition-api";
import { SplashPage } from "../../lib/vue-viewmodels";
export default createComponent({
async setup(props, context) {
await SplashPage.init(2000, context.root.$router, "plan", "login");
}
});
</script>
ERROR: "setup" must return a "Object" or a "Function", got "Promise"
There is a major caveat when working with asynchronous functions in Vue Composition API, that I believe many of you have ever come across. I have acknowledged it for a while from somewhere, but every time I want to have a detailed reference and share to others, I can’t find it’s documented anywhere.
When Vue mounts a component, it stores the instance in a global variable. When hooks been called inside the setup function, it will use the global variable to get the current component instance. With this approach, as long as the onMounted is called inside the component setup (), it will be able to get the instance of the current component.
Composition API is flexible enough, this shouldn’t be a problem. The most typical asynchronous operation is doing an AJAX request to the server. In the past years, some generic issues of AJAX have been solved or mitigated. The callback hell was extinguished with Promises and those were later sugared into async/await.
vue-async-computed can be installed through npm with the following command: Then, open the main.js file with your code editor. Import and use vue-async-computed: At this point, you will have a new Vue project that supports vue-async-computed.
The setup
function must be synchronous can be async
using Suspense.
An onMounted
hook can be used with an async
callback:
import { onMounted } from "@vue/composition-api";
// …
export default createComponent({
setup(props, context) {
onMounted(async () => {
await SplashPage.init(2000, context.root.$router, "plan", "login");
)};
}
});
Or, it is always possible to call an asynchronous function without to await it:
SplashPage.init(2000, context.root.$router, "plan", "login")
.catch(console.log);
In both cases, you'll have to take into account that the component will be rendered before the execution of the asynchronous function. A simple way to not display something that would depends on it is to use v-if
in your template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With