本文介绍了@vue-composition/如何在 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>

错误:setup"必须返回Object"或Function",得到Promise"

ERROR: "setup" must return a "Object" or a "Function", got "Promise"

推荐答案

setup 函数 可以使用Suspenseasync.

onMounted 钩子可以与 async 回调一起使用:

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);

在这两种情况下,您都必须考虑到组件将在执行异步函数之前呈现.一种不显示依赖于它的内容的简单方法是在模板中使用 v-if.

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.

这篇关于@vue-composition/如何在 setup() 中使用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:01