当我在 Vue.js 3 中使用 async setup() 时,为什么会得到空白(空)内容?

问题

我在 Vue.js 3 中使用 async setup(),但我的 HTML 内容消失了.我的组件模板没有插入 HTML,但是当我删除 async 和 await 前缀时,我的 HTML 内容又回来了.我该如何解决这个问题?

I use async setup() in Vue.js 3, but I got my HTML content to disappear. My component template did not insert to HTML, but when I remove the async and await prefix, my HTML content comes back. How can I fix this?

async setup () {
    const data = ref(null)
    try {
        const res = await fetch('api')
        data.value = res.json()
    }
    catch (e) {
        console.error(e)
    }
    return {
        data
    }
}

我试过了

  1. 我检查了 fetch,它返回了正确的响应
  2. 我试过<Suspense>标签,还是一样的问题
  1. I checked fetch, and it returned the correct response
  2. I've tried <Suspense> tag, but still the same problem

推荐答案

除了缺少的 await res.json() 之外,您的组件的 async setup() 看起来还不错,这仍然不会导致您看到的问题.我怀疑您对 <Suspense> 的使用不正确.

Your component's async setup() looks fine other than the missing await res.json(), which still wouldn't cause the problem you're seeing. I suspect your usage of <Suspense> is incorrect.

要在组件中使用 async setup(),父组件必须在 <Suspense> 标签中使用该组件:

To use async setup() in a component, the parent component must use that component in a <Suspense> tag:

<!-- Parent.vue -->
<template>
 <Suspense>
   <MyAsyncComponent />
 </Suspense>
</template>

您还可以使用 <Suspense>defaultfallback 插槽来在等待子组件设置时显示加载指示器解决:

You could also use the default and fallback slots of <Suspense> to show a loading indicator while waiting for the child component's setup to resolve:

<!-- Parent.vue -->
<template>
 <Suspense>
   <template #default>
     <MyAsyncComponent />
   </template>
   <template #fallback>
     <span>Loading...</span>
   </template>
 </Suspense>
</template>

演示

相关文章