mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-12 09:03:53 +00:00
60 lines
1.6 KiB
Markdown
60 lines
1.6 KiB
Markdown
# 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
|
|
|
|
```js
|
|
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`)
|
|
|
|
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.
|
|
|
|
This helper only works with:
|
|
- a component defined with `defineNuxtComponent`
|
|
- `<script setup nuxt>` syntax block
|
|
|
|
### Example
|
|
|
|
```vue
|
|
<template>
|
|
Page visits: {{ data.count }}
|
|
</template>
|
|
|
|
<script>
|
|
import { asyncData, defineNuxtComponent } from '@nuxt/app'
|
|
|
|
export default defineNuxtComponent({
|
|
setup () {
|
|
const { data } = asyncData('time', () => $fetch('/api/count'))
|
|
return { data }
|
|
}
|
|
})
|
|
</script>
|
|
```
|
|
|
|
When using with the `<script setup>` syntax, an addition attribute `nuxt` is required
|
|
|
|
```vue
|
|
<script setup nuxt>
|
|
import { asyncData } from '@nuxt/app'
|
|
|
|
const { data } = asyncData('time', () => $fetch('/api/count'))
|
|
</script>
|
|
|
|
<template>
|
|
Page visits: {{ data.count }}
|
|
</template>
|
|
```
|
|
|