为什么我在 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
}
}
我试过了
- 我检查了 fetch,它返回了正确的响应
- 我已经尝试了
标签,但还是同样的问题
- I checked fetch, and it returned the correct response
- I've tried
<Suspense>
tag, but still the same problem
你的组件的 async setup()
看起来不错,除了缺少 await res.json()
,这仍然不会导致您看到的问题.我怀疑您对
的使用不正确.
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()
,父组件必须在
标签中使用该组件:
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>
您还可以使用
的 default
和 fallback
插槽来显示加载指示器,同时等待子组件的设置解决:
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>