Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

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

Merged
merged 1 commit into from
Aug 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/content/2.guide/2.features/5.data-fetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' })
Expand Down
15 changes: 15 additions & 0 deletions test/fixtures/basic/pages/legacy/async-data.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<template>
<div>
{{ hello }}
</div>
</template>

<script>
export default defineNuxtComponent({
async asyncData () {
return {
hello: await $fetch('/api/hello')
}
}
})
</script>