useClientApiFetch

View source
仅客户端执行的 API 请求 composable,适用于非 SEO 敏感数据。

用法

使用自动导入的 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 阶段没有数据。初始渲染时 datanull,需使用 pendingstatus 管理加载状态。

示例

跳过 SSR,仅在浏览器 hydration 后发起请求;SSR 阶段无数据,初始 datanull

ready

client 模式:跳过 SSR,仅在浏览器挂载后发起请求

<script setup lang="ts">
interface Profile {
  id: string
  name: string
  email: string
}

const { data, pending, error, refresh } = useClientApiFetch<Profile>('/profile')
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="flex items-center gap-2 flex-wrap">
      <UBadge v-if="pending" color="warning" variant="subtle">
        pending
      </UBadge>
      <UBadge v-else-if="error" color="error" variant="subtle">
        error
      </UBadge>
      <UBadge v-else color="success" variant="subtle">
        ready
      </UBadge>
      <UButton size="sm" variant="outline" icon="i-lucide-refresh-cw" @click="refresh()">
        刷新
      </UButton>
    </div>
    <p class="text-xs text-muted">
      client 模式:跳过 SSR,仅在浏览器挂载后发起请求
    </p>
    <pre class="text-xs p-3 rounded bg-elevated overflow-auto">{{ error ? { error: error.message } : data }}</pre>
  </div>
</template>

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

Type Parameters

参数与 useApiFetch 相同。

Returns

返回值与 useApiFetch 相同。

Changelog

No recent changes
Copyright © 2025 - 2026 YiXuan - MIT License