useClientApiFetch
仅客户端执行的 API 请求 composable,适用于非 SEO 敏感数据。
Usage
使用自动导入的 useClientApiFetch composable 进行仅客户端的 API 请求。等价于 useApiFetch(url, { ...options, server: false, lazy: true })。
<script setup lang="ts">
interface UserPreferences {
theme: 'light' | 'dark'
language: string
notifications: boolean
}
// 客户端自动执行(hydration 后自动发起请求)
const { data, pending } = useClientApiFetch<UserPreferences>('/user/preferences')
// 手动控制执行时机(配合 immediate: false)
const { data: profile, execute } = useClientApiFetch<User>('/user/profile', {
immediate: false
})
onMounted(() => execute())
</script>
<template>
<div v-if="pending">加载中...</div>
<div v-else>{{ data }}</div>
</template>
useClientApiFetch继承useApiFetch的所有功能(认证、Toast、业务状态码检查等)。- 预设
server: false+lazy: true,请求不阻塞导航且仅在客户端执行。 - 默认 hydration 后自动发起请求。如需手动控制,额外传入
immediate: false。
由于
server: false 的特性,SSR 阶段没有数据。初始渲染时 data 为 null,需使用 pending 或 status 管理加载状态。API
useClientApiFetch()
useClientApiFetch<T = unknown, DataT = T>(url: string | (() => string), options?: UseApiFetchOptions<T, DataT>): UseApiFetchReturn<DataT>
创建仅客户端执行的 API 请求。
Parameters
url
string | (() => string) required
请求 URL 或返回 URL 的函数。
options
UseApiFetchOptions<T, DataT>
请求配置选项。完整选项参考
useApiFetch。以下选项会被强制设置,无法通过 options 覆盖:
server: false- 禁用服务端执行lazy: true- 启用 lazy 模式(不阻塞导航)
Type Parameters
参数与 useApiFetch 相同。
Returns
返回值与 useApiFetch 相同。