Why did I get blank (empty) content when I used async setup() in Vue.js 3?(当我在 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,它返回了正确的响应
- 我试过
<Suspense>
标签,还是一样的问题
- I checked fetch, and it returned the correct response
- 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>
的 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>
演示
这篇关于当我在 Vue.js 3 中使用 async setup() 时,为什么会得到空白(空)内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当我在 Vue.js 3 中使用 async setup() 时,为什么会得到空白(空)内容?
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
- 从原点悬停时触发 translateY() 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01