alova-client-usage
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese

Alova Client-Side Usage
Alova 客户端使用指南
For server-side (Node/Bun/Deno), seeskill. For alova openapi usage, seealova-serverskill.alova-openapi
服务端(Node/Bun/Deno)相关内容,请查看技能。 Alova OpenAPI 使用相关内容,请查看alova-server技能。alova-openapi
How to Use This Skill
如何使用本技能
This skill is structured in two layers:
- This file — Quick-reference index: what each API does and when to use it. Read this first.
- 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.
本技能分为两层结构:
- 本文档 —— 快速参考索引:介绍每个API的功能及适用场景。请先阅读此部分。
- 官方文档(按需获取) —— 如需了解完整选项、边缘情况或不熟悉的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 function | Parameters |
|---|---|
| GET | |
| POST | |
| PUT | |
| DELETE | |
| HEAD | |
| OPTIONS | |
| PATCH | |
Parameter Description:
- is the request path;
url - is the request body data;
data - is the request configuration object, which includes configurations such as request headers, params parameters, request behavior parameters, etc.;
config
In fact, the above functions calling are not sending request, but creates a method instance, which is a PromiseLike instance. You can use methods or to send request just like a Promise object.
then, catch, finallyawaitjavascript
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 | |
| POST | |
| PUT | |
| DELETE | |
| HEAD | |
| OPTIONS | |
| PATCH | |
参数说明:
- 为请求路径;
url - 为请求体数据;
data - 为请求配置对象,包含请求头、params参数、请求行为参数等配置;
config
实际上,调用上述函数并不会发送请求,而是创建一个方法实例,该实例是PromiseLike类型。你可以像使用Promise对象一样,调用方法或使用来发送请求。
then, catch, finallyawaitjavascript
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
| Hook | When to use | Docs |
|---|---|---|
| Fetch on mount, or trigger once on a user action (button click, form submit) | Docs |
| Re-fetch automatically when reactive state changes (search input, filter, tab, page) | Docs |
| Preload data silently in background, or refresh from outside the component that owns the data | Docs |
Business Strategy Hooks
业务场景Hooks
import from.alova/client
| Scenario | Hook | Key capability | Docs |
|---|---|---|---|
| Paginated list / infinite scroll | | Auto page management, preload next/prev, optimistic insert/remove/replace | Docs |
| Form submit (any complexity) | | Draft persistence, multi-step state sharing, auto-reset | Docs |
| Polling / focus / reconnect refresh | | Configurable triggers, throttle | Docs |
| Sms, email verification code send + countdown | | Cooldown timer built-in | Docs |
| Cross-component request trigger | | No prop-drilling or global store | Docs |
| Chained dependent requests | | Each step receives previous result | Docs |
| Retry with exponential backoff | | Configurable attempts + jitter | Docs |
| File upload with progress | | Concurrent limit, progress events | Docs |
| Server-Sent Events | | Reactive | Docs |
| Seamless data interaction | | interact with UI can be responded immediately without waiting | Docs |
从导入。alova/client
| 场景 | Hook | 核心能力 | 文档 |
|---|---|---|---|
| 分页列表 / 无限滚动 | | 自动分页管理、预加载前后页、乐观插入/删除/替换 | 文档 |
| 表单提交(任意复杂度) | | 草稿持久化、多步骤状态共享、自动重置 | 文档 |
| 轮询 / 聚焦 / 重连刷新 | | 可配置触发条件、节流控制 | 文档 |
| 短信、邮箱验证码发送 + 倒计时 | | 内置冷却计时器 | 文档 |
| 跨组件请求触发 | | 无需属性透传或全局状态管理 | 文档 |
| 链式依赖请求 | | 每一步接收上一步的结果 | 文档 |
| 指数退避重试 | | 可配置重试次数 + 抖动 | 文档 |
| 带进度的文件上传 | | 并发限制、进度事件 | 文档 |
| 服务器发送事件(SSE) | | 响应式 | 文档 |
| 无缝数据交互 | | 与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
全局和作用域缓存设置
- Fast in-page access, resets on refresh, Survive page refresh / offline-first, disable cache -> See Cache mode.
- Auto-invalidate after a mutation, on GET +
hitSourceon mutation Method -> See Auto Invalidate Cache.name - Manual invalidate -> See Manual invalidate.
- Set & Query cache -> See Operate Cache.
Key rule: prefer auto-invalidation — it requires zero imperative code and decouples components.
hitSourceHooks 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
常见问题
| Pitfall | Fix |
|---|---|
| Always wrap: |
| Only works while owning component is mounted; use |
| Cache ops called synchronously in v3 | |
| Set |
| 问题 | 解决方法 |
|---|---|
| 始终用函数包裹: |
| 仅在所属组件挂载时生效;否则使用 |
| v3中缓存操作同步调用无效果 | |
| 设置 |
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 before alova's hooks keep states on both ends in sync, which is the same effect as .
awaituseFetchjs
const { data } = await useRequest(getUser(1));在Alova的Hooks前使用,保持两端状态同步,效果与一致。
awaituseFetchjs
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'),
};
}在中直接await方法实例。
+page.server.[j|ts]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 . See Custom Method Key.
key通过设置更改缓存、请求共享和状态更新的匹配策略。查看 自定义方法Key。
key