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

g61*_*310 12 vue.js vue-component vuejs3 vue-composition-api

问题

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

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

我试过了

  1. 我检查了 fetch,它返回了正确的响应
  2. 我试过<Suspense>标签,但仍然是同样的问题

ton*_*y19 22

您的组件async setup()看起来不错,但缺少await res.json(),这仍然不会导致您看到的问题。我怀疑你的用法<Suspense>不正确。

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

<!-- Parent.vue -->
<template>
 <Suspense>
   <MyAsyncComponent />
 </Suspense>
</template>
Run Code Online (Sandbox Code Playgroud)

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

<!-- Parent.vue -->
<template>
 <Suspense>
   <template #default>
     <MyAsyncComponent />
   </template>
   <template #fallback>
     <span>Loading...</span>
   </template>
 </Suspense>
</template>
Run Code Online (Sandbox Code Playgroud)

已通过vue@3.0.0-0Node.js 14、Chrome 84、macOS v10.15 (Catalina) 验证。请注意,这<Suspense>仍然是实验性的,API 可能会发生变化。

演示


Sin*_*rus 5

文件parent.vue

<template>
  <!-- parent add <suspense> -->
  <suspense>
    <child />
  </suspense>
</template>

<script>
import Child from './child.vue'

export default {
  components: {
    child
  },
  setup() {
    return {}
  }
}
</script>

Run Code Online (Sandbox Code Playgroud)

文件child.vue

<template>
  <div>child</div>
</template>

<script>
export default {
  async setup() {
    return {}
  }
}
</script>

Run Code Online (Sandbox Code Playgroud)

用来。child.vueasync setup...对于parent.vue,您需要添加<suspense>child.vue.