mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-26 15:42:09 +00:00
e13baf9867
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
1.1 KiB
1.1 KiB
Data Fetching
Nuxt provides asyncData
to handle data fetching within you application.
asyncData
Within your pages and components you can use asyncData
to get access to data that resolves asynchronously.
Usage
asyncData(key: string, fn: () => Object, options?: { defer: boolean, server: boolean })
- key: a unique key to ensure that data fetching can be properly de-duplicated across requests
- fn an asynchronous function that must return an object.
- options:
- defer: whether to load the route before resolving the async function (defaults to
false
) - server: whether the fetch the data on server-side (defaults to
true
)
- defer: whether to load the route before resolving the async function (defaults to
Under the hood, defer: false
uses <Suspense>
to block the loading of the route before the data has been fetched. Consider using defer: true
and implementing a loading state instead for a snappier user experience.
Example
<script setup>
const { data } = await asyncData('time', () => $fetch('/api/count'))
</script>
<template>
Page visits: {{ data.count }}
</template>