useLazyFetch
此 useFetch 封装器可立即触发导航。
描述
¥Description
默认情况下,useFetch
会阻止导航,直到其异步处理程序解析完成。useLazyFetch
提供了一个 useFetch
的封装器,通过将 lazy
选项设置为 true
,可以在解析处理程序之前触发导航。
¥By default, useFetch
blocks navigation until its async handler is resolved. useLazyFetch
provides a wrapper around useFetch
that triggers navigation before the handler is resolved by setting the lazy
option to true
.
useLazyFetch
具有与 useFetch
相同的签名。在此模式下等待
useLazyFetch
仅确保调用已初始化。在客户端导航中,数据可能无法立即可用,你应该确保在应用中处理待处理状态。示例
¥Example
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
。