vue.jsasynchronousvuejs3vue-options-api

Using Suspense component in vue 3 along with Options API


The docs https://vuejs.org/guide/built-ins/suspense.html#async-components says in order to use Suspense Components, we need to make the components "Asynchronous".

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

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

But I am not sure how to make components Async using Options API.


Solution

  • With the Options API, the component is made an async component by using an async setup():

    export default {
        👇
      async setup() {
        const res = await fetch(...)
        const posts = await res.json()
        return {
          posts
        }
      }
    }
    

    That's actually documented just above the docs section the question links to.

    demo