useApiFetch

基于 Nuxt useFetch 封装的 API 请求 composable,提供自动认证、业务状态码检查和 Toast 提示。
查看源码

用法

使用自动导入的 useApiFetch composable 进行 API 请求,基于 Nuxt useFetch 封装,提供自动认证、数据解包、业务状态码检查和统一的错误处理。

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

// 基础用法(自动解包 data 字段)
const { data, pending, error, refresh } = await useApiFetch<User[]>('/users')

// POST 请求
const { data } = await useApiFetch('/users', {
  method: 'POST',
  body: { name: 'test', email: 'test@example.com' }
})

// 使用其他端点
const { data } = await useApiFetch('/users', { endpoint: 'v2' })
</script>
  • useApiFetch 继承 Nuxt useFetch 的所有功能,同时提供额外的 API 集成特性。
  • 自动从 session 获取 token 并添加到请求头(通过 $api 实例)。
  • 自动检查业务状态码并抛出错误。
  • 内置 Toast 提示,支持自定义配置。

数据请求模式

Movk Nuxt 提供三种数据请求 composable,签名一致,按执行时机选择:

Composable执行时机阻塞导航场景
useApiFetchSSR + CSR是首屏核心数据
useLazyApiFetchSSR + CSR否次要 / 非首屏数据
useClientApiFetch仅 CSR否非 SEO 敏感数据

useApiFetch 在 SSR 阶段就发起请求,首屏直出数据:

error
{
  "error": "toast.add is not a function"
}
<script setup lang="ts">
interface Profile {
  id: string
  name: string
  email: string
  role: string
}

const { data, pending, error, refresh } = await useApiFetch<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>
    <pre class="text-xs p-3 rounded bg-elevated overflow-auto">{{ error ? { error: error.message } : data }}</pre>
  </div>
</template>

数据解包与转换

useApiFetch 接收到的已是 $api 解包后的业务数据,泛型 T 直接声明该数据类型;transform 接收解包后的数据做二次转换:

// 泛型 T 直接声明业务数据类型(即 data 字段的类型)
const { data } = await useApiFetch<User>('/user')
// data.value = { id: 1, name: 'test' }

// 结合 transform 做二次转换
const { data } = await useApiFetch<{ content: User[] }, SelectItem[]>('/users', {
  transform: ({ content }) => content.map(u => ({ label: u.name, value: u.id }))
})
解包机制、unwrap / businessCheck 的交互示例见 $api 页

业务状态码检查

$api 拦截器自动检查业务状态码,不在 successCodes 中时抛出 ApiError(见下方错误分类)。传 businessCheck: false 关闭校验,但仍解包 dataKey 字段:

const { data } = await useApiFetch('/external', {
  businessCheck: false
})

整个端点都不返回信封时,在端点 response 上声明,免去逐请求传参:

const { data } = await useApiFetch<SensorPoint[]>('/point-numbers', { endpoint: 'sensor' })
端点级声明与优先级见 $api 页

错误分类

所有失败统一为 ApiError(NuxtError<ApiErrorData>),经 useAsyncData 时原样保留;按 error.value.data.kind 区分场景。下拉切换错误类型观察 error.value 形态:

  • business:HTTP 200 但 code 不在 successCodes 内,data.code 保留原始业务码。
  • http-400 / http-500:kind 为 http,statusCode 为对应码;GET 的 5xx 会按 ofetch 默认重试一次,错误只上报一次。
  • http-422:data.response 携带服务端补充信息。
  • network:连接被强制断开,请求拿不到响应。
  • timeout:超出 timeout 设定的毫秒数。

所有失败统一为 ApiError(NuxtError),按 error.data.kind 区分场景。

<script setup lang="ts">
const props = defineProps<{
  mode: 'business' | 'http-400' | 'http-422' | 'http-500' | 'network' | 'timeout'
}>()

const urlMap: Record<typeof props.mode, string> = {
  'business': '/demo/errors?type=business',
  'http-400': '/profile?fail=1',
  'http-422': '/demo/errors?type=422',
  'http-500': '/demo/errors?type=500',
  'network': '/demo/errors?type=network',
  'timeout': '/demo/errors?type=slow'
}

const { error, execute } = useApiFetch(() => urlMap[props.mode], {
  immediate: false,
  toast: false,
  retry: 0,
  timeout: 500
})

const info = computed(() => {
  const err = error.value
  if (!err) return null
  return {
    kind: err.data?.kind,
    statusCode: err.statusCode,
    message: err.message,
    code: err.data?.code ?? null,
    response: err.data?.response ?? null
  }
})
</script>

<template>
  <div class="flex flex-col gap-3">
    <UButton size="sm" color="error" variant="outline" icon="i-lucide-circle-alert" @click="execute()">
      触发 {{ mode }}
    </UButton>
    <p class="text-xs text-muted">
      所有失败统一为 <code>ApiError</code>(NuxtError),按 <code>error.data.kind</code> 区分场景。
    </p>
    <pre class="text-xs p-3 rounded bg-elevated overflow-auto">{{ info }}</pre>
  </div>
</template>

Toast 提示

toast 选项支持请求级配置:false 全关、{ success: false } 仅留错误、successMessage / errorMessage 快捷文本,或传完整 Toast 属性(color、icon、duration 等):

// 关闭 Toast / 仅保留错误提示 / 快捷文本
await useApiFetch('/users', { toast: false })
await useApiFetch('/users', { toast: { success: false } })
await useApiFetch('/users', {
  toast: { successMessage: '创建成功!', errorMessage: '创建失败,请重试' }
})

// 完整 Toast 属性
await useApiFetch('/users', {
  toast: {
    success: { title: '创建成功', color: 'success', icon: 'i-lucide-circle-check' },
    error: { title: '创建失败', color: 'error', duration: 5000 }
  }
})

// 全局关闭成功提示时,单次请求用 show: true 开启
await useApiFetch('/users', { toast: { success: { show: true } } })

// 自定义文案同样是开启意图:全局关闭或方法未命中白名单时也会弹出
await useApiFetch('/users', { toast: { successMessage: '创建成功!' } })
开关优先级:请求级 show 显式声明 > 请求级 successMessage / errorMessage > 全局 success.show / error.show / methods > 全局 enabled。全局配置为 toast.success.show: false 时,请求级传 { success: { show: true } } 或 { successMessage: '...' } 都会弹出;要明确静默请传 { success: false } 或 { success: { show: false } }。
只想为 POST / PUT / PATCH / DELETE 弹成功提示,请在全局或端点配置 toast.success.methods;该字段不接受请求级传入
五种 Toast 模式的交互示例见 $api 页

API

useApiFetch()

useApiFetch<T = unknown, DataT = T>(url: string | (() => string), options?: UseApiFetchOptions<T, DataT>): UseApiFetchReturn<DataT>

创建 API 请求。

Parameters

url
string | (() => string) required
请求 URL 或返回 URL 的函数。支持响应式 URL。
options
UseApiFetchOptions<T, DataT>
请求配置选项。支持所有 Nuxt useFetch 选项,以及额外的 API 集成选项。

Type Parameters

T
type
业务数据类型(已由 $api 自动解包)。即 API 响应中 data 字段的数据类型。
DataT
type
transform 转换后的最终类型。默认等于 T。

Returns

返回 useFetch 的响应对象,包含以下属性:

data
Ref<DataT | null>
响应数据(已解包和转换)。初始值为 null,请求成功后更新为实际数据。
error
Ref<ApiError | null>
错误对象。所有失败统一为 ApiError,按 data.kind 区分业务、HTTP、网络与超时错误。
status
Ref<'idle' | 'pending' | 'success' | 'error'>
请求状态。
  • 'idle' - 尚未开始(仅 immediate: false 时)
  • 'pending' - 请求进行中
  • 'success' - 请求成功
  • 'error' - 请求失败
pending
Ref<boolean>
是否正在请求中。等价于 status.value === 'pending'。
refresh
(opts?: { dedupe?: boolean }) => Promise<void>
刷新数据,重新执行请求。别名: execute。
execute
(opts?: { dedupe?: boolean }) => Promise<void>
refresh 的别名。手动执行请求(常用于 immediate: false 时)。
clear
() => void
清空状态。将 data 设为 null、error 设为 null、status 设为 'idle'。

Changelog

No recent changes

useLazyApiFetch

用法

使用自动导入的 useLazyApiFetch composable 进行 API 请求,等价于 useApiFetch(url, { ...options, lazy: true })。lazy 模式下请求不会阻塞客户端导航,页面立即显示,数据在后台加载。

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

// 懒加载用户数据
const { data, status } = useLazyApiFetch<User[]>('/users')
</script>

<template>
  <div>
    <div v-if="status === 'pending'">
      加载中...
    </div>
    <div v-else-if="status === 'error'">
      加载失败
    </div>
    <div v-else-if="data">
      <div v-for="user in data" :key="user.id">
        {{ user.name }}
      </div>
    </div>
  </div>
</template>
  • useLazyApiFetch 不会阻塞客户端导航,适合非关键数据(如用户列表、评论等)。
  • 客户端导航时 data 初始为 null,status 为 'pending',需要处理加载状态。
  • 继承 useApiFetch 的所有功能(认证、Toast、业务状态码检查等)。
对于首屏必需的数据,应使用 useApiFetch(非 lazy 模式),以阻塞导航确保数据就绪。
完整的 API 选项和功能说明请参考 useApiFetch 文档

示例

页面先渲染、随后进入 pending,data 在拿到响应前为 null,需配合 pending / status 处理加载态:

error

lazy 模式:页面先渲染再进入 pending;data 在拿到响应前为 null

{
  "error": "toast.add is not a function"
}
<script setup lang="ts">
interface Profile {
  id: string
  name: string
  email: string
}

const { data, pending, error, refresh } = useLazyApiFetch<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">
      lazy 模式:页面先渲染再进入 pending;data 在拿到响应前为 null
    </p>
    <pre class="text-xs p-3 rounded bg-elevated overflow-auto">{{ error ? { error: error.message } : data }}</pre>
  </div>
</template>

API

useLazyApiFetch()

useLazyApiFetch<T = unknown, DataT = T>(url: string | (() => string), options?: UseApiFetchOptions<T, DataT>): UseApiFetchReturn<DataT>

创建懒加载的 API 请求。

Parameters
url
string | (() => string) required
请求 URL 或返回 URL 的函数。支持响应式 URL。
options
UseApiFetchOptions<T, DataT>
请求配置选项。支持所有 useApiFetch 的选项。
lazy 选项会被强制设为 true,无需手动指定。
Type Parameters
T
type
业务数据类型(已由 $api 自动解包)。
DataT
type
transform 转换后的最终类型。默认等于 T。
Returns

返回值与 useApiFetch 相同。

Changelog

No recent changes

useClientApiFetch

用法

使用自动导入的 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 管理加载状态。

示例

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

pending

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