useLazyFetch
此围绕 useFetch 的包装器会立即触发导航。
描述
默认情况下,useFetch
会阻塞导航,直到其异步处理程序解析完成。 useLazyFetch
提供了一个围绕 useFetch
的包装器,它通过将 lazy
选项设置为 true
来在处理程序解析之前触发导航。
useLazyFetch
与 useFetch
具有相同的签名。示例
pages/index.vue
<script setup lang="ts">
/* Navigation will occur before fetching is complete.
* Handle 'pending' and 'error' states directly within your component's template
*/
const { status, data: posts } = await useLazyFetch('/api/posts')
watch(posts, (newPosts) => {
// Because posts might start out null, you won't have access
// to its contents immediately, but you can watch it.
})
</script>
<template>
<div v-if="status === 'pending'">
Loading ...
</div>
<div v-else>
<div v-for="post in posts">
<!-- do something -->
</div>
</div>
</template>
useLazyFetch
是编译器转换的保留函数名,因此您不应将自己的函数命名为 useLazyFetch
。