docs: add information on how to use options api asyncData (#7019)

This commit is contained in:
Daniel Roe 2022-08-29 11:02:24 +01:00 committed by GitHub
parent 2d071eb48c
commit 0087e7bbe0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 0 deletions

View File

@ -173,6 +173,27 @@ const refresh = () => refreshNuxtData('count')
</script>
```
## Options API support
Nuxt 3 provides a way to perform `asyncData` fetching within the Options API. You must wrap your component definition within `defineNuxtComponent` for this to work.
```vue
<script>
export default defineNuxtComponent({
fetchKey: 'hello',
async asyncData () {
return {
hello: await $fetch('/api/hello')
}
}
})
</script>
```
::alert{type=warning}
Options API support for `asyncData` may well change before the stable release of Nuxt 3.
::
## Isomorphic `fetch` and `$fetch`
When we call `fetch` in the browser, user headers like `cookie` will be directly sent to the API. But during server-side-rendering, since the `fetch` request takes place 'internally' within the server, it doesn't include the user's browser cookies, nor does it pass on cookies from the fetch response.

View File

@ -171,6 +171,14 @@ describe('head tags', () => {
// })
})
describe('legacy async data', () => {
it('should work with defineNuxtComponent', async () => {
const html = await $fetch('/legacy/async-data')
expect(html).toContain('<div>Hello API</div>')
expect(html).toContain('{hello:"Hello API"}')
})
})
describe('navigate', () => {
it('should redirect to index with navigateTo', async () => {
const { headers } = await fetch('/navigate-to/', { redirect: 'manual' })

View File

@ -0,0 +1,15 @@
<template>
<div>
{{ hello }}
</div>
</template>
<script>
export default defineNuxtComponent({
async asyncData () {
return {
hello: await $fetch('/api/hello')
}
}
})
</script>