mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-11 08:33:53 +00:00
docs: add examples for useLazyFetch
and useLazyAsyncData
(#3418)
This commit is contained in:
parent
52d22feaea
commit
0958a61322
@ -71,6 +71,24 @@ const { data } = await useAsyncData('count', () => $fetch('/api/count'))
|
||||
|
||||
This composable behaves identically to `useAsyncData` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function).
|
||||
|
||||
### Example
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div>
|
||||
{{ pending ? 'Loading' : count }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
const { pending, data: count } = useLazyAsyncData('count', () => $fetch('/api/count'))
|
||||
watch(count, (newCount) => {
|
||||
// Because count starts out null, you won't have access
|
||||
// to its contents immediately, but you can watch it.
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## `useFetch`
|
||||
|
||||
Within your pages, components and plugins you can use `useFetch` to universally fetch from any URL.
|
||||
@ -121,6 +139,30 @@ const { data } = await useFetch('/api/count')
|
||||
|
||||
This composable behaves identically to `useFetch` with the `lazy: true` option set. In other words, the async function does not block navigation. That means you will need to handle the situation where the data is `null` (or whatever value you have provided in a custom `default` factory function).
|
||||
|
||||
### Example
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<!-- you'll need to handle a loading state -->
|
||||
<div v-if="pending">
|
||||
Loading ...
|
||||
</div>
|
||||
<div v-else>
|
||||
<div v-for="post in posts">
|
||||
<!-- do something -->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
const { pending, data: posts } = useLazyFetch('/api/posts')
|
||||
watch(posts, (newPosts) => {
|
||||
// Because posts starts out null, you won't have access
|
||||
// to its contents immediately, but you can watch it.
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
## Isomorphic fetch
|
||||
|
||||
When we call `fetch` in the browser, user headers like `cookie` will be directly sent to the API.
|
||||
|
Loading…
Reference in New Issue
Block a user