在 vue 3 中使用 Suspense 组件和选项 API

Using Suspense component in vue 3 along with Options API

文档 https://vuejs.org/guide/built-ins/suspense.html#async-components 说为了使用 Suspense 组件,我们需要使组件“异步”。

<script setup>
const res = await fetch(...)
const posts = await res.json()
</script>

<template>
  {{ posts }}
</template>

但我不确定如何使用选项使组件异步 API。

使用选项 API,通过使用 async setup():

使组件成为 async 组件
export default {
    
  async setup() {
    const res = await fetch(...)
    const posts = await res.json()
    return {
      posts
    }
  }
}

这实际上记录在问题链接到的文档部分的上方。

demo

如文档所述,仅支持 async setup 函数和异步 script setup。选项 API 是旧版,不应包含新功能。

source code中可以看出,只支持setup

可能可以访问内部组件实例并遵循 setup 的工作方式,例如:

beforeCreate() {
  this.$.asyncDep = promise;
},

但这是一种未经记录的骇人听闻的方式,可能会在没有通知的情况下被破坏。