alova-client-usage

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
alova banner
alova banner

Alova Client-Side Usage

Alova 客户端使用指南

For server-side (Node/Bun/Deno), see
alova-server
skill. For alova openapi usage, see
alova-openapi
skill.
服务端(Node/Bun/Deno)相关内容,请查看
alova-server
技能。 Alova OpenAPI 使用相关内容,请查看
alova-openapi
技能。

How to Use This Skill

如何使用本技能

This skill is structured in two layers:
  1. This file — Quick-reference index: what each API does and when to use it. Read this first.
  2. Official docs (fetch on demand) — For full options, edge cases, or unfamiliar APIs, fetch the URL listed in each section to get the latest accurate information.
Always fetch the official doc before answering questions about specific API options or behaviors — alova is actively developed and live docs are more reliable than training data.

本技能分为两层结构:
  1. 本文档 —— 快速参考索引:介绍每个API的功能及适用场景。请先阅读此部分。
  2. 官方文档(按需获取) —— 如需了解完整选项、边缘情况或不熟悉的API,请访问各章节中列出的URL以获取最新准确信息。
在回答特定API选项或行为相关问题前,请务必查阅官方文档 —— Alova 正处于活跃开发阶段,在线文档比训练数据更可靠。

Installation & Setup

安装与配置

See references/SETUP.md for:
  • Installation
  • Creating Alova instance
  • Framework-specific StatesHook
  • Request adapters
  • Global request sharing and timeout
  • Create interceptor about Token-based login, logout and token refresh
  • cache logger
  • limit number of method snapshots
如需了解以下内容,请查看 references/SETUP.md
  • 安装
  • 创建Alova实例
  • 框架专属StatesHook
  • 请求适配器
  • 全局请求共享与超时设置
  • 创建基于Token的登录、登出及令牌刷新拦截器
  • 缓存日志器
  • 限制方法快照数量

Create Method Instance

创建方法实例

alova provides a total of 7 request types.
Instance creation functionParameters
GET
alovaInstance.Get(url[, config])
POST
alovaInstance.Post(url[, data[, config]])
PUT
alovaInstance.Put(url[, data[, config]])
DELETE
alovaInstance.Delete(url[, data[, config]])
HEAD
alovaInstance.Head(url[, config])
OPTIONS
alovaInstance.Options(url[, config])
PATCH
alovaInstance.Patch(url[, data[, config]])
Parameter Description:
  • url
    is the request path;
  • data
    is the request body data;
  • config
    is the request configuration object, which includes configurations such as request headers, params parameters, request behavior parameters, etc.;
In fact, the above functions calling are not sending request, but creates a method instance, which is a PromiseLike instance. You can use
then, catch, finally
methods or
await
to send request just like a Promise object.
javascript
alovaInstance
  .Get('/api/user')
  .then((response) => {
    // ...
  })
  .catch((error) => {
    // ...
  })
  .finally(() => {
    // ...
  });

// or
try {
  await userMethodInstance;
} catch (error) {
  // ...
} finally {
  // ...
}
See Method Documentation if need to know full method instance API.
Alova 提供共7种请求类型。
实例创建函数参数
GET
alovaInstance.Get(url[, config])
POST
alovaInstance.Post(url[, data[, config]])
PUT
alovaInstance.Put(url[, data[, config]])
DELETE
alovaInstance.Delete(url[, data[, config]])
HEAD
alovaInstance.Head(url[, config])
OPTIONS
alovaInstance.Options(url[, config])
PATCH
alovaInstance.Patch(url[, data[, config]])
参数说明:
  • url
    为请求路径;
  • data
    为请求体数据;
  • config
    为请求配置对象,包含请求头、params参数、请求行为参数等配置;
实际上,调用上述函数并不会发送请求,而是创建一个方法实例,该实例是PromiseLike类型。你可以像使用Promise对象一样,调用
then, catch, finally
方法或使用
await
来发送请求。
javascript
alovaInstance
  .Get('/api/user')
  .then((response) => {
    // ...
  })
  .catch((error) => {
    // ...
  })
  .finally(() => {
    // ...
  });

// or
try {
  await userMethodInstance;
} catch (error) {
  // ...
} finally {
  // ...
}
如需了解完整的方法实例API,请查看 方法文档

Method Metadata

方法元数据

Add additional information to specific method instances to facilitate their identification or additional information in global interceptor such as different response returning, global toast avoiding. please set method metadata. See -> Method Metadata.
为特定方法实例添加额外信息,以便在全局拦截器中识别它们或添加额外处理(如不同的响应返回、避免全局提示),请设置方法元数据。查看 -> 方法元数据

Core Hooks

核心Hooks

Use these hooks in components instead of hand-rolling common request patterns.
import from
alova/client
.
HookWhen to useDocs
useRequest
Fetch on mount, or trigger once on a user action (button click, form submit)Docs
useWatcher
Re-fetch automatically when reactive state changes (search input, filter, tab, page)Docs
useFetcher
Preload data silently in background, or refresh from outside the component that owns the dataDocs
在组件中使用这些Hooks,替代手动实现常见的请求模式。
alova/client
导入。
Hook适用场景文档
useRequest
组件挂载时获取数据,或在用户操作(按钮点击、表单提交)时触发一次请求文档
useWatcher
当响应式状态变化时(搜索输入、筛选、标签页、分页)自动重新获取数据文档
useFetcher
在后台静默预加载数据,或在数据所属组件外部刷新数据文档

Business Strategy Hooks

业务场景Hooks

import from
alova/client
.
ScenarioHookKey capabilityDocs
Paginated list / infinite scroll
usePagination
Auto page management, preload next/prev, optimistic insert/remove/replaceDocs
Form submit (any complexity)
useForm
Draft persistence, multi-step state sharing, auto-resetDocs
Polling / focus / reconnect refresh
useAutoRequest
Configurable triggers, throttleDocs
Sms, email verification code send + countdown
useCaptcha
Cooldown timer built-inDocs
Cross-component request trigger
actionDelegationMiddleware
+
accessAction
No prop-drilling or global storeDocs
Chained dependent requests
useSerialRequest
/
useSerialWatcher
Each step receives previous resultDocs
Retry with exponential backoff
useRetriableRequest
Configurable attempts + jitterDocs
File upload with progress
useUploader
Concurrent limit, progress eventsDocs
Server-Sent Events
useSSE
Reactive
data
+
readyState
Docs
Seamless data interaction
useSQRequest
interact with UI can be responded immediately without waitingDocs
alova/client
导入。
场景Hook核心能力文档
分页列表 / 无限滚动
usePagination
自动分页管理、预加载前后页、乐观插入/删除/替换文档
表单提交(任意复杂度)
useForm
草稿持久化、多步骤状态共享、自动重置文档
轮询 / 聚焦 / 重连刷新
useAutoRequest
可配置触发条件、节流控制文档
短信、邮箱验证码发送 + 倒计时
useCaptcha
内置冷却计时器文档
跨组件请求触发
actionDelegationMiddleware
+
accessAction
无需属性透传或全局状态管理文档
链式依赖请求
useSerialRequest
/
useSerialWatcher
每一步接收上一步的结果文档
指数退避重试
useRetriableRequest
可配置重试次数 + 抖动文档
带进度的文件上传
useUploader
并发限制、进度事件文档
服务器发送事件(SSE)
useSSE
响应式
data
+
readyState
文档
无缝数据交互
useSQRequest
与UI交互可立即响应,无需等待文档

Cache Strategy

缓存策略

Alova has L1 (memory) and L2 (persistent/restore) layers, plus automatic request sharing (dedup).
Alova 拥有 L1(内存)和 L2(持久化/恢复)两层缓存,加上自动请求共享(去重)功能。

Set cache globally and scoped

全局和作用域缓存设置

Key rule: prefer
hitSource
auto-invalidation — it requires zero imperative code and decouples components.
  • 页面内快速访问、刷新时重置、跨页面刷新存活/离线优先、禁用缓存 -> 查看 缓存模式
  • 数据变更后自动失效,GET请求的
    hitSource
    + 变更方法的
    name
    -> 查看 自动失效缓存
  • 手动失效 -> 查看 手动失效
  • 设置与查询缓存 -> 查看 操作缓存
核心原则:优先使用
hitSource
自动失效机制 —— 无需命令式代码,且实现组件解耦。

Hooks Middleware

Hooks 中间件

Middleware allows you to intercept and control request behavior in useHooks. Common scenarios include:
  • Ignoring requests under certain conditions
  • Transforming response data
  • Changing request method or forcing cache bypass
  • Error handling (capture or throw custom errors)
  • Controlling response delays
  • Modifying reactive states (loading, data, etc.)
  • Implementing request retry logic
  • Taking full control of loading state
For full middleware API and examples, see Request Middleware.
中间件允许你在使用Hooks时拦截并控制请求行为。常见场景包括:
  • 在特定条件下忽略请求
  • 转换响应数据
  • 更改请求方法或强制绕过缓存
  • 错误处理(捕获或抛出自定义错误)
  • 控制响应延迟
  • 修改响应式状态(加载状态、数据等)
  • 实现请求重试逻辑
  • 完全控制加载状态
如需了解完整的中间件API及示例,请查看 请求中间件

Mock Request

模拟请求

Setup mock data for specific requests. See Mock Request.
为特定请求设置模拟数据。查看 模拟请求

Best Practices

最佳实践

  • Create multiple alova instances for different domains, APIs, or environments.
  • Provide a folder that uniformly stores request functions, to keep your code organized.
  • prefer using hooks in components, directly call method instance in other places.
  • prefer binding hooks events with chain calling style, like
    useRequest(method).onSuccess(...).onError(...)
    .
  • 为不同域名、API或环境创建多个Alova实例。
  • 提供统一的文件夹存储请求函数,保持代码结构清晰。
  • 优先在组件中使用Hooks,在其他场景直接调用方法实例。
  • 优先使用链式调用风格绑定Hooks事件,例如
    useRequest(method).onSuccess(...).onError(...)

Common Pitfalls

常见问题

PitfallFix
useWatcher
first arg is a Method instance
Always wrap:
() => method(state.value)
updateState
silently does nothing
Only works while owning component is mounted; use
setCache
otherwise
Cache ops called synchronously in v3
await invalidateCache / setCache / queryCache
useWatcher
doesn't fetch on mount
Set
immediate: true
问题解决方法
useWatcher
的第一个参数是方法实例
始终用函数包裹:
() => method(state.value)
updateState
无响应
仅在所属组件挂载时生效;否则使用
setCache
v3中缓存操作同步调用无效果
await invalidateCache / setCache / queryCache
useWatcher
挂载时不触发请求
设置
immediate: true

TypeScript

TypeScript支持

Annotate the response shape on the Method instance — hooks infer from it automatically:
ts
const getUser = (id: number) => alovaInstance.Get<User>(`/users/${id}`);
// or need to transform data.
const getUser = (id: number) =>
  alovaInstance.Get(`/users/${id}`, {
    transform(user: User) {
      return {
        ...user,
        name: user.lastName + ' ' + user.firstName,
      };
    },
  });

const { data } = useRequest(getUser(1)); // data: Ref<User>
在方法实例上标注响应数据结构 —— Hooks会自动推断类型:
ts
const getUser = (id: number) => alovaInstance.Get<User>(`/users/${id}`);
// 或需要转换数据时
const getUser = (id: number) =>
  alovaInstance.Get(`/users/${id}`, {
    transform(user: User) {
      return {
        ...user,
        name: user.lastName + ' ' + user.firstName,
      };
    },
  });

const { data } = useRequest(getUser(1)); // data: Ref<User>

SSR Component Party

SSR 组件适配

alova can manage APIs on both server and client, instead using different request solutions on the server and client sides respectively.
Alova 可同时在服务端和客户端管理API,无需在服务端和客户端分别使用不同的请求方案。

CSR

CSR

Generally, alova's hooks only work in client side.
js
// won't send request in server side.
useRequest(getUser(1));
通常,Alova的Hooks仅在客户端生效。
js
// 服务端不会发送请求。
useRequest(getUser(1));

Nextjs

Nextjs

directly await method instance in server components.
js
const App = async () => {
  const data = await alovaInstance.Get('/todo/list');
  // then ... code
  return <div>{...}</div>;
};
export default App;
在服务端组件中直接await方法实例。
js
const App = async () => {
  const data = await alovaInstance.Get('/todo/list');
  // then ... code
  return <div>{...}</div>;
};
export default App;

Nuxt

Nuxt

Using
await
before alova's hooks keep states on both ends in sync, which is the same effect as
useFetch
.
js
const { data } = await useRequest(getUser(1));
在Alova的Hooks前使用
await
,保持两端状态同步,效果与
useFetch
一致。
js
const { data } = await useRequest(getUser(1));

Sveltekit

Sveltekit

directly await method instance in
+page.server.[j|ts]
.
js
/** @type {import('./$types').PageServerLoad} */
export async function load({ params }) {
  return {
    list: alovaInstance.Get('/todo/list'),
  };
}
+page.server.[j|ts]
中直接await方法实例。
js
/** @type {import('./$types').PageServerLoad} */
export async function load({ params }) {
  return {
    list: alovaInstance.Get('/todo/list'),
  };
}

Custom Adapter

自定义适配器

If all preset adapters not meet your needs, custom your own adapter.
如果所有预设适配器都无法满足需求,可自定义适配器。

Custom Method Key

自定义方法Key

Change cache, request sharing and state updating matching strategy by setting
key
. See Custom Method Key.
通过设置
key
更改缓存、请求共享和状态更新的匹配策略。查看 自定义方法Key