为什么我在 Vue.js 3 中使用 async setup() 时得到空白(空)内容? [英] Why did I get blank (empty) content when I used async setup() in Vue.js 3?

查看:68
本文介绍了为什么我在 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. 我已经尝试了 标签,但还是同样的问题
  1. I checked fetch, and it returned the correct response
  2. 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>

您还可以使用 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>

演示

这篇关于为什么我在 Vue.js 3 中使用 async setup() 时得到空白(空)内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆