Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@vue-composition / How can I use asynchronous methods in setup()

<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"

like image 941
邵励治 Avatar asked Feb 14 '20 16:02

邵励治


People also ask

Is it possible to work with asynchronous functions in Vue composition API?

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.

How to get the current instance of a component in Vue?

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.

Is composition API asynchronous?

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.

How do I use Vue-async-computed?

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.


1 Answers

The setup function must be synchronous can be async using Suspense.

How to avoid using async setup (obsolete answer)

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.

like image 148
Paleo Avatar answered Oct 27 '22 00:10

Paleo