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

邵励治 picture 邵励治 · Feb 14, 2020 · Viewed 8.3k times · Source
<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"

Answer

Paleo picture Paleo · Feb 17, 2020

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.